为什么向 Django 模型声明管理器会导致“对象”无效?

发布于 2024-10-08 00:14:19 字数 689 浏览 4 评论 0原文

我已经为以下模型声明了一个管理器,但是这样做之后,我无法再使用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)

错误是类型对象“List”没有属性“objects”

I have declared a manager to the following model, but after doing so, I can no longer use List.objects.get(). Anybody know why?

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

  archived_lists = ArchivedListManager()
  active_lists = ActiveListManager()

And the managers:

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)

The error is type object 'List' has no attribute 'objects'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨光如昨 2024-10-15 00:14:19

正如 Django 文档中所述:

如果您使用自定义 Manager 对象,请注意 Django 遇到的第一个 Manager (按照它们在模型中定义的顺序)具有特殊状态。 Django 将类中定义的第一个 Manager 解释为“默认”Manager,并且 Django 的多个部分将专门为该模型使用该 Manager 。因此,最好谨慎选择默认管理器,以避免重写 get_query_set() 导致无法检索您想要使用的对象的情况。

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

不过,解决方案很简单:只需将其添加

objects = models.Manager()

到您的模型类中即可。

As noted in the 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.

So as far as "why" goes, it's to allow you to provide your own default manager.

The solution is simple, though: just add this

objects = models.Manager()

to your model class.

猫卆 2024-10-15 00:14:19

添加您自己的管理器会抑制创建库存管理器。

“经理名称”

Adding your own manager suppresses creation of the stock manager.

"Manager names"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文