What is the preferred way to filter CharField using List of Tags? in database i have something like this :
genres = "something, apple ,something_else ,something_else2, orange, grape, more.."
i tried using __in
operator nothing comes out
elem = list(Elements.objects.filter(genres__in=['apple','orange','grape']))
You can try this query
elem = list(Elements.objects.filter(Q(genres__icontains="apple") | Q(genres__icontains="orange") | Q(genres__icontains="grape")))
But I think for tags it's a better solution Django Filtering A Blog Based on Tags
You would probably want to use a Q lookup. https://docs.djangoproject.com/en/2.1/topics/db/queries/#complex-lookups-with-q-objects
from django.db.models import Q
elem = Elements.objects.filter(Q(genres__icontains="apple") | Q(genres__icontains="orange") | Q(genres__icontains="grapes"))
I was able to get what i want doing the following:
from django.db.models import Q
from functools import reduce
from operator import and_
tag_list = ['apple', 'orange', 'grape']
query = reduce(and_, (Q(genres__icontains=tag) for tag in tag_list))
elem = list(Elements.objects.filter(query))
You can also use or_
operator see:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.