'RelatedManager'对象没有属性 [英] 'RelatedManager' object has no attribute

查看:216
本文介绍了'RelatedManager'对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的模型:

I have a model defined like this:

class UserDetail(models.Model):
    user = models.ForeignKey(User, db_index=True, unique=True, related_name='details')
    favourites = models.ManyToManyField(Article, related_name='favourited_by', blank=True)

我正在尝试执行以下操作:

And I'm trying to do something like this:

article = get_object_or_404(Article, pk=id)
request.user.details.favourites.add(article)

为什么不起作用?

我遇到此错误:


'RelatedManager'对象没有属性'favourites'

'RelatedManager' object has no attribute 'favourites'

我猜详细信息不是正确的类型,但是为什么不是呢?以及如何执行这样的查询?

I guess details isn't the right type, but why isn't it? And how can I perform a query like that?

推荐答案

访问 user.details ,它将访问 UserDetail.user 外键的后向引用。外键本身没有指定 User 只能有一个 UserDetail ,因此django为您提供了 RelatedManager ,您可以像常规的 Manager 一样对其进行过滤和查询。因此,您对 .objects 经理执行的操作相同。您可以要求 user.details.all() user.details.filter() user.details.get(),依此类推,根据方法和结果,将为您提供查询集,对象或异常。

When you access user.details, it accesses the backreference of the UserDetail.user foreign key. The foreign Key itself doesn't specify that a User can only have one UserDetail, so django gives you a RelatedManager, which you can filter and query just like a regular Manager. So you do the same things to it that you do to your .objects managers. You can ask for user.details.all(), user.details.filter(), user.details.get(), and so on, which will either give you a queryset, an object, or an exception,depending on the method and the results.

这篇关于'RelatedManager'对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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