从queryset值访问django模板中的外键

时间:2013-08-08 06:16:30

标签: python django

我似乎无法找到我做错了什么。这是我的设置

from django.db import models
from django.conf import settings

"""
Simple model to handle blog posts
"""
class Category(models.Model):

    def __unicode__(self):
        return self.name

    name = models.CharField(max_length=50)

class BlogEntry(models.Model):

    def __unicode__(self):
        return self.blog_post_name

    blog_post_name = models.CharField(max_length=200)
    blog_post_content = models.CharField(max_length=1024)
    blog_pub_date = models.DateTimeField(auto_now=True)
    blog_post_image = models.ImageField(upload_to = settings.MEDIA_ROOT, default = '/media_files/douche.jpg')
    blog_post_category = models.ForeignKey(Category)


views.py

    from django.shortcuts import render
    from blog_post.models import BlogEntry, Category
    from blog_post.forms import BlogPostForm
    from django.shortcuts import HttpResponseRedirect
    from time import gmtime, strftime

    """
    This method will display all user posts (newest first)
    """
    def home(request):
         blog_template = "blogs.html"
         list_all_posts = BlogEntry.objects.all().order_by('-blog_pub_date').values() # List all posts on DB ordered by date (newest first).
    return render(request, blog_template, locals())

在模板上,我可以访问blog_post_category_id的值,但我想显示该类别的实际名称。

我在模板上尝试了set.all

{% extends "base.html" %}
{% load split_string %}
{% block content %}
<div class="row">
    <div class="large-6 columns">
        {% if list_all_posts %}

        {% for post in list_all_posts %}
        <ul class="pricing-table">
            <li class="title">{{ post.blog_post_name }}</li>
            <li class="bullet-item">
            <a class="fancybox" href="/media_files/{{ post.blog_post_image|img_path_last_value:'/' }}" title="{{ post.blog_post_content }}" >
                <img src="/media_files/{{ post.blog_post_image|img_path_last_value:'/' }}" alt="" />
            </a>
            </li>
            {% for cat in post.category_set.all %}
            <li class="price">{{ cat.category_name }}</li>
            {% endfor %}
            <li class="description">{{ post.blog_post_content}}</li>
        </ul>
        {% endfor %}
        {% endif %}

    </div>
</div>
{% endblock %}

有人可以对此有所了解吗?

提前致谢。

2 个答案:

答案 0 :(得分:9)

来自docs

.values()Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

这意味着你将无法调用post.category_set.all因为post是字典而不是模型实例,你需要指定字典中包含的字段,当你这样做时你可以包含blog_post_category__name将在模板中显示类别名称。

答案 1 :(得分:2)

list_all_posts = BlogEntry.objects.all().order_by('-blog_pub_date').values()

您必须明白,当您对查询集执行.values()时,Django会从SQL关系中收集值并将其存储在字典中。因此存储外键的ID,但任何其他信息都丢失了!

所以你有很多工作要做。这有两个解决方案:

1)将填充了给定数据的词典返回到模板:

例如:.values('blog_post_name', 'blog_post_category__name')

2)返回仅包含所需数据的查询集

例如:.only('blog_post_name').select_related('blog_post_category__name')

当您尝试在查询集中显示模板内的类别名称时, select_related 可以避免Django再次调用数据库