[Django]-Default filter in Django model

41👍

You’ll have to override the manager:

class MyModelManager(models.Manager):
    def get_queryset(self):
        return super(MyModelManager, self).get_queryset().filter(active=True)

class MyModel(models.Model):
    timestamp = models.DateTimeField(default=datetime.utcnow)
    active = models.BooleanField(default=True)

    objects = MyModelManager()

    class Meta:
        ordering = ['-timestamp']

get_queryset was get_query_set before Django 1.6

4👍

I was able to accomplish what I wanted by adding managers to the model. I also created an abstract base class to make it easier to add this to other models without having to replicate the same code – here is the modified example:

class MyActiveManager(models.Manager):
    def get_queryset(self):
        return super(MyModelManager, self).get_queryset().filter(active=True)

class MyInactiveManager(models.Manager):
    def get_queryset(self):
        return super(MyModelManager, self).get_queryset().filter(active=False)

class AbstractModel(models.Model):
    timestamp = models.DateTimeField(default=datetime.utcnow)
    active = models.BooleanField(default=True)

    objects = MyActiveManager()
    objects_inactive = MyInactiveManager()
    objects_all = models.Manager()

    class Meta:
        abstract = True
        ordering = ['-timestamp']

class MyModel(AbstractModel):
    # Define active-enabled model here

Now, any model I want to have an "active" (and "timestamp" in this example) field can just inherit from the base model. When I use MyModel.objects.all() – I get all objects with active=True – this is especially useful if I already have alot of code using the objects manager. If I want only inactive results, I use MyModel.objects_inactive.all(), and if I want all records regardless of the value of active, I use MyModel.objects_all.all()

Leave a comment