gpt4 book ai didi

django - 为什么将管理器声明为 Django 模型,无效 "objects"

转载 作者:行者123 更新时间:2023-12-04 16:28:02 25 4
gpt4 key购买 nike

我已经声明了以下模型的经理,但这样做后,我不能再使用 List.objects.get() .有人知道为什么吗?

class List(models.Model):
title = models.CharField(max_length=20, unique=True)
archived = models.BooleanField()

archived_lists = ArchivedListManager()
active_lists = ActiveListManager()

和经理:
class ArchivedListManager(models.Manager):
def get_query_set(self):
return super(ArchivedListManager, self).get_query_set().filter(archived=True)

class ActiveListManager(models.Manager):
def get_query_set(self):
return super(ActiveListManager, self).get_query_set().filter(archived=False)

错误是 type object 'List' has no attribute 'objects'

最佳答案

Django docs 中所述:

If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets the first Manager defined in a class as the "default" Manager, and several parts of Django will use that Manager exclusively for that model. As a result, it's a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_query_set() results in an inability to retrieve objects you'd like to work with.



因此,就“为什么”而言,它允许您提供自己的默认管理器。

不过,解决方案很简单:只需添加这个
objects = models.Manager()

到您的模型类。

关于django - 为什么将管理器声明为 Django 模型,无效 "objects",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4455330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com