Django documents state we can override default queryset using manager's get_queryset method.
What if I user models.Queryset and as.manager method to avoid duplicate methods. How can I override default query?
It seems get_queryset method of models.Queryset doesnt seems to work in this case.
Thanks.
You can use a combination of a Manager
and a QuerySet
to achieve this, like so:
# model_managers.py
class CustomManager(models.Manager):
""" Enables changing the default queryset function. """
def get_queryset(self):
# Here you can change the default queryset function
return super(CustomManager, self).get_queryset(example_field=True)
class CustomQuerySet(models.QuerySet):
""" Include additional queryset functions. """
def example_filter(self):
return self.filter(other_field=False)
# models.py
class YourModel(models.Model):
# Override the default manager
objects = CustomManager.from_queryset(CustomQuerySet)() # The pair of empty parenthesis is required!
And then you can use it anywhere like:
# Will filter `example_field`
YourModel.objects.all()
# Will filter `example_field` and `other_field`
YourModel.objects.example_filter()
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