0

I have a model which has an active field, and i want to filter out all records which are inactive basing on this field. Let's say:

Record(Model):
    active = BooleanField()
    ...

to filter them out i can do:

Record.objects(active=True)

But it is a general case and i want inactive records to be filtered out almost any time. What is the best way to follow DRY principle and do not filter every request i do manually like in example above and in meantime keep the ability to manage inactive records in admin panel.

4

1 回答 1

1

您可以使用Managers来完成此任务:

# First, define the Manager subclass.
class ActiveManager(models.Manager):
    def get_query_set(self):
        return super(ActiveManager, self).get_query_set().filter(active=True)

# Then hook it into the Record model explicitly.
class Record(models.Model):
    active = BooleanField()

    objects = models.Manager() # The default manager.
    active_objects = ActiveManager() # The specific manager.

#to filter for all active records you can do:
Record.active_objects.all()
于 2012-10-13T15:14:28.837 回答