无法通过模型实例访问管理器 [英] Manager isn't accessible via model instances

查看:29
本文介绍了无法通过模型实例访问管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在另一个模型中获取模型对象实例,但出现此错误:

I'm trying to get model objects instance in another one and I raise this error :

 Manager isn't accessible via topic instance

这是我的模型:

class forum(models.Model):
    # Some attributs

class topic(models.Model):
    # Some attributs

class post(models.Model):
    # Some attributs

    def delete(self):
        forum = self.topic.forum
        super(post, self).delete()
        forum.topic_count = topic.objects.filter(forum = forum).count()

这是我的看法:

def test(request, post_id):
    post = topic.objects.get(id = int(topic_id))
    post.delete()

我得到:

post.delete()
forum.topic_count = topic.objects.filter(forum = forum).count()
Manager isn't accessible via topic instances

推荐答案

当您尝试通过模型的实例访问模型的 Manager 时,会导致有问题的错误.您使用了小写 类名.这使得很难判断错误是否是由访问 Manager 的实例引起的.由于可能导致此错误的其他情况未知,因此我假设您以某种方式混淆了 topic 变量,以便您最终指向 topic 的实例> 模型而不是类.

The error in question is caused when you try to access the Manager of a model through an instance of the model. You have used lower case class names. This makes it hard to say if the error is caused by an instance accessing the Manager or not. Since other scenarios that can cause this error are unknown I am proceeding on the assumption that you have somehow mixed up the topic variable so that you end up pointing to an instance of the topic model instead of the class.

这一行是罪魁祸首:

forum.topic_count = topic.objects.filter(forum = forum).count()
#                   ^^^^^

你必须使用:

forum.topic_count = Topic.objects.filter(forum = forum).count()
#                   ^^^^^
#                   Model, not instance.

怎么了?objects 是在类级别可用的 Manager,而不是实例.有关详细信息,请参阅文档检索对象.金钱报价:

What is going wrong? objects is a Manager available at the class level, not to the instances. See the documentation for retrieving objects for details. Money quote:

Managers只能通过模型类而不是从模型实例访问,以强制分离表级"操作和记录级"操作.

Managers are accessible only via model classes, rather than from model instances, to enforce a separation between "table-level" operations and "record-level" operations.

(强调)

更新

请参阅下面来自@Daniel 的评论.对类名使用标题大小写是一个好主意(不,你必须:P).例如 Topic 而不是 topic.无论您是指实例还是类,您的类名都会引起一些混淆.由于 Manager 不能通过 访问.实例 非常具体,我能够提供解决方案.错误可能并不总是那么不言自明.

See the comments from @Daniel below. It is a good idea (nay, you MUST :P) to use title case for class names. For instance Topic instead of topic. Your class names cause some confusion whether you are referring to an instance or a class. Since the Manager isn't accessible via <model> instances is very specific I am able to offer a solution.The error may not be so self evident always.

这篇关于无法通过模型实例访问管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆