亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Django中獲取上下文的鍵值?

如何在Django中獲取上下文的鍵值?

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


查看完整回答
反對 回復 2022-09-13
  • 1 回答
  • 0 關注
  • 76 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號