Modify default queryset in django

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)