![](/img/trans.png)
[英]Get an attribute in a template from a ManyToMany relationship in Django
[英]Django: Determining ManyToMany Relationship in Template
我建立了一个如此的ForeignKey
关系:
class WatchList(models.Model):
user = models.ForeignKey(User)
class Thing(models.Model)
watchlist = models.ForeignKey(WatchList, null=True, blank=True)
这使我可以有条件地在模板中显示不同的消息,如下所示:
{% if thing.watchlist.user != request.user %}
Something
{% else %}
Nothing
{% endif %}
但是,现在我将我的关系从ForeignKey
更改为ManyToManyField
,这种模板内过滤不再起作用:
class WatchList(models.Model):
user = models.ForeignKey(User)
class Thing(models.Model)
watchlist = models.ManyToManyField(WatchList)
在模板中尝试这种类型的templatetag过滤会发现AttributeError: 'ManyRelatedManager' object has no attribute 'user'
。
我如何过滤具有ManyToMany关系的模板中的对象,以便在{% if thing.watchlist.user != request.user %}
可以显示不同的消息?
尝试更换
{% if thing.watchlist.user != request.user %}
通过
{% if request.user not in thing.watchlist.user.all %}
因为现在您已经建立了m2m关系,所以用户列表不仅仅是一个。 因此.all
将返回用户列表,而不是m2m对象(不确定它是一个对象,不知道如何调用它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.