12👍
✅
If you want to dynamically build the list of queries, you could have a sequence like this:
request = Q(name_contains='franz')
if condition1:
request |= Q(birthdate_date=date(2005, 5, 2))
if condition2:
request |= Q(param3_contains='lorem')
Then:
Students.objects.get(request)
If you need something even more generic, you could have a function that passes a dict, like:
conditions = {'name_contains': 'franz',
'birthdate_date': date(2005, 5, 2),
'param3_contains': 'lorem'}
And build the condition like this (Untested):
request = None
for key, value in conditions.items():
new_request = Q(**{key: value})
if request: request |= new_request
else: request = new_request
1👍
I have a similar requirement in my application. I have to search for a searchterm in all kinds of names:
Qterm = Q(firstname__icontains=searchterm) | \
Q(lastname__icontains=searchterm) | \
Q(resume__icontains=searchterm) | \
Q(companyname__icontains=searchterm))
or, if you want to match one field to a number of searchterms:
Qterm = Q()
for term in ["robot", "animatronic", "automaton"]:
Qterm |= Q(rolename_icontains=term)
fieldname_icontains
ultimately becomes a LIKE
. There are also more criteria, like that the user should be ‘active’, which is a boolean field:
Qactive = Q(active=True)
At the end, I combine all these Q objects like this:
Qs = Qterm & Qactive & Qthis & Qthat
…and I retrieve my active users like this:
userlst = Users.objects.filter(Qs)
I hope this helps!
- [Django]-Django autocomplete_fields doesn't work in TabularInline (but works in StackedInline)
- [Django]-Is it possible to use query parameters on the Django Admin Site
- [Django]-Get selected values of ManytoMany field in django model save method
- [Django]-When running Celery with Django's manage.py command, it returns a strange error
- [Django]-Encrypt and Decrypt information in a cookie
Source:stackexchange.com