I want to make a query, something like
Model.objects.filter(x=x).filter(y=y).filter(z=z)
... but there are some cases when for example y
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.