ZeroSoul13
ZeroSoul13

Reputation: 99

Acess Foreign key on django template from queryset values

I just can't seem to find what i'm doing wrong. Here's my setup

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())

On the template i can access the value of blog_post_category_id but i would like to show the actual name of the category.

I've tried on the template the 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 %}

Can anyone shed some light on this?

Thanks in advance.

Upvotes: 2

Views: 7393

Answers (2)

Ricola3D
Ricola3D

Reputation: 2442

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

You must understand that when you do a .values() on the queryset, Django gathers the values from the SQL relation and stores it in a dictionnary. Thus is stores the ID of the foreign key, but anyother information is lost !

So you've many work arounds. Here are two solutions:

1) Return a dict filled with the given data to the templates:

E.g.: .values('blog_post_name', 'blog_post_category__name')

2) Return a queryset with the wanted data only

E.g.: .only('blog_post_name').select_related('blog_post_category__name')

The select_related is here to avoid Django to call the DB again when you try to display the category name inside a template from the queryset

Upvotes: 2

CJ4
CJ4

Reputation: 2535

From the docs

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

This means you will not be able to call post.category_set.all because post is a dictionary not a model instance, you need to specify the fields included in the dictionary and when you do you could include blog_post_category__name which will show the category name in the template.

Upvotes: 10

Related Questions