我尝试查询以获取所有帖子主题。每个帖子属于多个主题。我得到了这个,但我不知道如何传递给模板。这是我的代码。在模板中,我得到了帖子,但我无法访问单个帖子的主题。感谢您的帮助。models.pyclass Post(models.Model): title = models.CharField(unique=True, max_length=121) content = models.TextField() published = models.DateField(default=timezone.now) def __str__(self): return self.titleclass Topic(models.Model): topic_name = models.CharField(primary_key=True,unique=True, max_length=60) posts = models.ManyToManyField(Post) def __str__(self): return self.topic_nameviews.pydef codinglife(request): posts = Post.objects.filter(topic__topic_name__contains='codinglife') #Get posts belong topic 'codinglife' context = { 'posts': Post.objects.filter(topic__topic_name__contains='codinglife') } # for each post get topic this post belong many topic for post in posts: context[post.id] = Topic.objects.filter(posts=post) return render(request, 'site/topiclistview.html', context)模板{% extends "site/base.html" %}{% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ post.published }}</small> {% comment 'need to show topic her' %} {% endcomment %} </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %}{% endblock content %}
1 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
无需在您的视图中执行任何特殊操作(但请参阅下文),您只需要使用反向关系:
{% for post in posts %}
<small class="text-muted">{{ post.published }}</small>
<ul>
{% for topic in post.topic_set.all %}
<li>{{ topic.name }}</li>
{% endfor %}
</ul>
<h2><a class="article-title" href="#">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
{% endfor %}
现在,这可以通过在您的视图中使用select_related来优化一点,以避免执行1 + N db查询。
添加回答
举报
0/150
提交
取消