问题描述
默认情况下,我想只返回已发布实例(published = True)。是否有可能重写.objects以便MyModel.objects.all()实际上返回MyModel.objects.filter(published = True)?
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.filter(published=True)?
这明智吗?
推荐答案
您可以通过编写自定义代码来实现-只需覆盖 get_queryset
方法并将对象
设置为Manager实例。例如:
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()
请参见了解详情。如果这是您惯常的默认情况,那是明智的。要取消发布,请创建另一个管理器,您可以使用 MyModel.unpublished_objects
之类的内容进行访问。再次,文档中提供了有关此类事物的示例。
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.
这篇关于是否可以在Django模型上覆盖.objects?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!