How to filter by all in queryset
I've got a queryset within a function. In some cases, I want to filter by a specific model.
cars = Car.objects.filter(model='Toyota')
In other cases, I don't want to filter by this field at all. Eg. (Syntax is wrong, but it demonstrates what I'm after)
cars = Car.objects.filter(model=all)
How do I include a field within a queryset as shown above, but prevent it from limiting the results?
Thanks!
You can write a custom manager for your model and modify filter()
.
from django.db import models
class NewManager(models.Manager):
def filter(self, **kwargs):
if kwargs == {'model': 'all'}
return self.all()
else:
return self.filter(**kwargs)
And define the new manager in the model.
Here is more details about manager.