Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default queryset with using as_manager

Tags:

django

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.

like image 358
durdenk Avatar asked Sep 10 '17 21:09

durdenk


1 Answers

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()
like image 86
durdenk Avatar answered Nov 15 '22 22:11

durdenk