Warm tip: This article is reproduced from stackoverflow.com, please click
django

General rule for Django model class to always exclude "unpublished" instances

发布于 2020-03-27 10:15:32

I'm searching a way to make some rule to exclude certain instances in each queryset. To follow DRY and to be sure that I(or some one else) will not accidentally include not accepted instances in queries. I'm relatively new in Djnago and didn't find the api to resolve this problem.

class SomeClassModel(models.Model):
    value = models.CharField(max_length=244)
    accepted = models.BooleanField(default=False)

How could I(or some one else) exclude not accepted instances from all queries? Even if I do SomeClassModel.objects.all()

Questioner
khashashin
Viewed
78
Jon Clements 2019-07-05 21:34

You can use a ModelManager and override the default objects, eg:

class ExcludeNotAccepted(models.Manager):
    def get_queryset(self):
        return super().get_queryset().exclude(accepted=False)

class SomeClassModel(models.Model):
    value = models.CharField(max_length=244)
    accepted = models.BooleanField(default=False)

    # make the default objects exclusive of non-accepted
    objects = ExcludeNotAccepted()
    # still allow explicit access via another name
    all_objects = models.Manager()

This will have the desired effect of when accessing SomeClassModel.objects.all() of automatically filtering out non-accepted items, but you can still access all objects by explicitly using SomeClassModel.all_objects.all()...