I try to query to get all of Topic of Post. Each Post belong multiple Topic. I got this but i don't know how to pass to Template. This is my code. In template i got posts but i can't access topics of single posts. Thank for help.
models.py
class 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.title
class 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_name
views.py
def 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)
Template
{% 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 %}
No need to do anything special in your views (but see below though), you just have to use the reverse relationship :
{% 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 %}
Now this can optimized a bit by using select_related
in your view to avoid doing 1+N db queries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.