19๐
I do not know, if I get your question, but
Model.objects.filter(x=x, y__isnull = False, z=z)
gives you the queryset, where the y
column is non-null (IS NOT NULL
).
Hereโs the relevant documentation.
EDIT: Check if y is None and build your queryset dynamically:
if y is None:
qs = Model.objects.filter(x=x).filter(z=z)
elif z is None:
qs = Model.objects.filter(x=x).filter(y=y)
...
If there are too many arguments to deal with, you could use something like this; assuming that x
, y
, z
are stored in a dictionary your values
:
your_values = { 'x' : 'x value', 'y' : 'y value', 'z' : 'value'}
arguments = {}
for k, v in your_values.items():
if v:
arguments[k] = v
Model.objects.filter(**arguments)
5๐
Something like this could work:
models = Model.objects.all()
variables = {'x':'x','y':'y','z':'z'}
for key, value in variables.items():
if key=='x' and value:
models = models.filter(x=value)
if key=='y' and value:
models = models.filter(y=value)
if key=='z' and value:
models = models.filter(z=value)
Because QuerySets are lazy, this doesnโt involve any database activity.
- Deploying Django Channels with Daphne + NGINX using SSL
- Django formset set current user
- RuntimeError: Never call result.get() within a task Celery
- How to alter/change the post data in django UpdateView
- Django Limit ManytoMany queryset based on selected FK
4๐
A better approach on the otherwise very readable @rolling-stone answer:
models = Model.objects.all()
variables = {'x':x,'y':y,'z':z}
for key, value in variables.items():
if value is not None:
models = models.filter(**{key: value})
Anyway, depending on the specific filter, youโll need to apply filters together in the same .filter() call, so the โblindโ way only works in the simple cases. See https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships for more information on those cases.
- Django Rest Framework override model fields in modelserialzer
- How should I represent a bit flags int field in django admin?
- Converting DateTimeField in Django to Unix time
- How to throttle Django error emails
2๐
You can create a model manager and then assign it to your model so that you can use this manager to any model. This solution is more pythonic.
class GridManager(models.Manager):
def applyFilters(self, *args, **kwargs):
new_kwargs = {}
for eachKey in kwargs:
val = kwargs[eachKey]
if val != '' and val != None:
new_kwargs[eachKey] = val
if new_kwargs:
return super(GridManager, self).get_query_set().filter(*args, **new_kwargs)
else:
return super(GridManager, self).get_query_set()
Assign this manager to your model:
class some_model(models.Model):
your fields.....
......
objects = models.Manager()
grid_manager = GridManager()
And in your view you can use the above manager as:
objects = some_model.grid_manager.applyFilters(x=value, y = value, z = None)
Now you donโt have to worry about the none values. Hope this helps.
0๐
You can write:
filters = {'x':'abc', 'y':None, 'z':2}
# here we filter out the None values of the dict
filters = dict(filter(lambda (k, v): v is not None, filters.items()))
# We use the dict to create the query
qs = Model.objects.filter(**filters)
- Foreign Key to User model
- Pass a custom queryset to serializer in Django Rest Framework
- DJANGO_SETTINGS_MODULE No Module Named
- Django: updating a column, saved in a variable name
- How can I hide a django label in a custom django form?