19👍
Here’s one way to get an always true Q object:
always_true = ~Q(pk__in=[])
The ORM optimizer recognises that Q(pk__in=[])
always evaluates to False, and the ~
negates it to make it True.
4👍
as Alasdair answered in comment:
Obj.filter(
Q(some_f1=some_v1) if some else Q(),
f1=v1,
f2=v2,
f3=v3,
f4=v4,
...
)
3👍
Try this;
conditions = {'f1':f1,'f2':f2, 'f3':f3}
if some:
conditions['some_f1'] = some_v1
Obj.objects.filter(**conditions)
- How to download a filefield file in django view
- Test if ValidationError was raised
- Is there a way to set the id value of new Django objects to start at a certain value?
1👍
Based on this answer we can make conditional argument passing
Obj.filter(
*( (Q(some_f1=some_v1),) if some else ()),
f1=v1,
f2=v2,
f3=v3,
f4=v4,
...
)
So, if some
is True
we add tuple (Q(some_f1=some_v1),)
to arguments list, in other case we add empty tuple ()
, also we need to wrap it in *()
, as always when we passing tuple of non-keyword args
- Django admin validation for inline form which rely on the total of a field between all forms
- Django Formset.is_valid() failing for extra forms
1👍
An “always true” Q object is equivalent to No Q object when using AND (basic filter syntax; i.e. x and True == x
), thus a DRYer alternative for your use case is as follows:
filters = dict(f1=v1,
f2=v2,
f3=v3,
f4=v4,
...)
if some:
filters['some_f1'] = some_v1
qs = obj.filter(**filters)
Modify according to your needs.
- Django template img src not working
- Why does docker-compose build not reflect my django code changes?
- How to specify uniqueness for a tuple of field in a Django model
- SQL injection hacks and django
- Django tests complain of missing tables
0👍
Since QuerySets are lazy, you can create the default filter, and then add others base on your conditions. Django won’t run the query until the QuerySet is evaluated (for example, iterating through it in a for loop)
filtered_objects = Obj.filter(
some_f1=some_v1,
f1=v1,
f2=v2,
f3=v3,
f4=v4,
...
)
if some:
filtered_objects.filter(some_f1=some_v1)
- Error while accessing sqlite3 shell from django application
- Is there a Django template tag that lets me set a context variable?