[Fixed]-Override default queryset with using as_manager

12๐Ÿ‘

โœ…

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()
๐Ÿ‘คdurdenk

1๐Ÿ‘

You should show what you tried that didnโ€™t work.

But nevertheless, you just need to use that call to define your own manager in the model:

class MyModel(models.Model):
    ...
    objects = MyQuerySet.as_manager()
๐Ÿ‘คDaniel Roseman

0๐Ÿ‘

You can create manage class by inheriting models.Manager and then you can define your own query set method.

in model.py, we should assign class as property as given below:

example = ExampleManager()

Now we can use example instead of objects and can call respective ExampleManager method.

๐Ÿ‘คKapil

Leave a comment