我嘗試查詢以獲取所有帖子主題。每個帖子屬于多個主題。我得到了這個,但我不知道如何傳遞給模板。這是我的代碼。在模板中,我得到了帖子,但我無法訪問單個帖子的主題。感謝您的幫助。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
提交
取消