I have a model of objects. I also have a list of options to filter results with. I'm not sure if there is an easy way to filter the objects in the model such that any object that matches any of the items in the filter list is returned. For example:
# returns all users with name starting with 'P'
usersWithPName = User.objects.filter(name__startswith = 'P')
# 3 letters to filter User model with
filterList = ['P', 'T', 'R']
# ideally would return all users with name starting with either 'P', 'T', or 'R'
usersWithPTRName = User.objects.filter(name__startswith = filterList)
Is there any way to filter (in this case) the User model such that any object matching any one of the items in the filterList is returned?
Definition and Usage. The exact lookup is used to get records with a specified value. The exact lookup is case sensitive. For a case insensitive search, use the iexact lookup.
values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.
A GROUP BY in Django is used with the AGGREGATE functions or the built-ins. The GROUP BY statement and aggregate functions like COUNT, MAX, MIN, SUM, AVG are used in a combo to group the result – set by one or more columns. ORDER BY column _ name (s); Understanding this clause using the DJANGO GROUP BY Cheat Sheet.
Saving changes to objects To save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .
This can be done with Q objects
from django.db.models import Q
usersWithPTRName = User.objects.filter(Q(name__startswith='P') |
Q(name__startswith='T') |
Q(name__startswith='R'))
Also you can build Q filters at runtime:
filterList = ['P', 'T', 'R']
query = Q()
for letter in filterList:
query = query | Q(name__startswith=letter)
usersWithPTRName = User.objects.filter(query)
You can use python reduce
and operator
builtins:
import operator
from functools import reduce
from django.db.models import Q
values = ["blue", "green", "brown"]
# or condition
conditions = reduce(operator.or_, [Q(**{"categories__slug": value}) for value in values])
# and condition
conditions = reduce(operator.and_, [Q(**{"categories__slug": value}) for value in values])
queryset = queryset.filter(conditions)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With