开发者

Is it possible to override .objects on a django model?

I'd like to by default only return "published" instances (published=True). Is it possible to override .objects so that MyModel.objects.all() actually returns MyModel.objects.filte开发者_如何学Pythonr(published=True)?

Is this sensible? How would I get the unpublished ones in the rare cases where I did want them?


You can do this by writing a custom Manager -- just override the get_queryset method and set your objects to a Manager instance. For example:

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

class MyModel(models.Model):
    # fields
    # ...

    objects = MyModelManager()

See the docs for details. It's sensible if that's going to be your usual, default case. To get unpublished, create another manager which you can access with something like MyModel.unpublished_objects. Again, the docs have examples on this type of thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜