create dynamic query set using Django query
this case performs "AND" operation. but some time value is blank or NULL.
example:- user model have name, age, and city three columns. and perform operation filter but this and query is dynamic some time 3 fields available or sometimes one or maybe two how to write a dynamic query.
You can use Q()
from django.db.models import Q
query = Q()
if need_filter_name:
query &= Q(name='my_name')
if need_filter_age:
query &= Q(age='my_age')
if need_filter_city:
query &= Q(city='my_city')
User.objects.filter(query)
If you need OR operator use query |= Q()
For AND operator use query &= Q()
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