【发布时间】:2019-10-16 08:56:08
【问题描述】:
我正在尝试以相反的顺序在模板上显示 ManyToMany 字段。
这就是我的意思:
当 ManyToMany 字段是模型中使用的字段时,我设法在模板上显示 ManyToMany 字段,例如:
<br/>{% for tag in post.tag.all %}{{ tag }}<br/>{% endfor %}
将基于此模型显示帖子所属的所有标签(即类别):
class Post(models.Model):
tag = models.ManyToManyField(Tag,blank=True,null=True,related_name='tag')
现在我想要一些相反的东西 - 当 ManyToMany 字段位于 Author 模型中时显示帖子的作者(上面的帖子模型保持不变):
class Person(models.Model):
post=models.ManyToManyField(Post,blank=True,null=True,related_name='post')
我很确定它与相关对象引用有关 (https://docs.djangoproject.com/en/2.2/ref/models/relations/)
就是做不出来。
我已经在模板上尝试了以下内容。
{% for post in posts %}
{% for author in post.person_set.all %}{{author}}<br/>{% endfor %}
{% endfor %}
另外,我应该像上面那样在模板上进行这种搜索,还是将这种搜索放在视图中更好的做法...资源方面。
感谢您的帮助。
【问题讨论】:
-
由于您已将
related_name设置为'post'(这不是 一个好主意),您应该写{% for author in post.post.all %},但真正的错误是您这样做了related_names 的工作很糟糕。 -
你不需要在关系的两边都定义ManyToManyField。选择一个。
-
@DanielRoseman:我不相信他会这样做,
Post中的 m2m 指的是Tag,而不是Person。 -
没有双重引用。 :)
标签: django