如何在Django中获取上下文的键值?

我尝试查询以获取所有帖子主题。每个帖子属于多个主题。我得到了这个,但我不知道如何传递给模板。这是我的代码。在模板中,我得到了帖子,但我无法访问单个帖子的主题。感谢您的帮助。


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)

模板


{% 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 %}


烙印99
浏览 83回答 1
1回答

翻过高山走不出你

无需在您的视图中执行任何特殊操作(但请参阅下文),您只需要使用反向关系:{% for post in posts %}&nbsp; &nbsp; &nbsp;<small class="text-muted">{{ post.published }}</small>&nbsp; &nbsp; &nbsp;<ul>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{% for topic in post.topic_set.all %}&nbsp; &nbsp; &nbsp; &nbsp;<li>{{ topic.name }}</li>&nbsp; &nbsp; &nbsp; &nbsp;{% endfor %}&nbsp; &nbsp; &nbsp;</ul>&nbsp; &nbsp; &nbsp; <h2><a class="article-title" href="#">{{ post.title }}</a></h2>&nbsp; &nbsp; &nbsp; &nbsp; <p class="article-content">{{ post.content }}</p>{% endfor %}现在,这可以通过在您的视图中使用select_related来优化一点,以避免执行1 + N db查询。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python