Modify default queryset in django

Question:

I have added a ‘cancelled’ field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?

Asked By: juanefren

||

Answers:

You can do this with a custom model manager and override the get_queryset function to always filter canceled=False.

class CustomManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(canceled=False)

class MyModel(models.Model):
    # Blah blah
    objects = CustomManager()

Then when calling MyModel.objects.all() it will always exclude canceled objects. Here is a blog post I found helpful on the subject. http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/

EDIT:
Perhaps a better approach with a custom manager would be to attach it to another property, other than objects, such as:

class MyModel(models.Model):
    # Blah blah
    active = CustomManager()

And in your views your queries would look like MyModel.active.all().

EDIT2:
Updated method spelling from get_query_set to get_queryset for modern versions of django.

Answered By: Mark Lavin

You could write custom query manager, but I don’t believe this is the right way to go. This would make an implicit, hidden condition for a filter, which would make code unreadable. Remember Zen of Python: Explicit is better than implicit. Detect places, where you need to add cancelled=False and just add this, that’s the way you should do this.

Answered By: gruszczy