Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default filter in Django model

Is is possible to set a default filter in Django models?

Something like:

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

    class Meta:
        ordering = ['-timestamp']
        filtering = [active=True]
like image 517
SimonSays Avatar asked Feb 17 '13 19:02

SimonSays


1 Answers

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

like image 90
Pavel Anossov Avatar answered Sep 17 '22 03:09

Pavel Anossov