scre_www
scre_www

Reputation: 2692

Django: how to use a queryset and display results in a template?

I'm struggling with Django QuerySets. This is a JSON dump of my Database with data:

[
{
    "fields": {
        "label_number": "1",
        "label_type": "A",
        "label_desc_nl": "NL Text",
        "label_desc_en": "EN Text",
        "label_desc_de": "DE Text",
        "label_desc_pl": "PL Text",
        "label_desc_es": "ES Text",
        "label_desc_fr": "FR Text",
        "label_desc_it": "IT Text",
        "label_desc_pt": "PT Text",
        "label_desc_cs": "CS Text"
    },
    "model": "myapp.labels",
    "pk": 1
},
{
    "fields": {
        "label_number": "1",
        "label_type": "B",
        "label_desc_nl": "NL Text",
        "label_desc_en": "EN Text",
        "label_desc_de": "DE Text",
        "label_desc_pl": "PL Text",
        "label_desc_es": "ES Text",
        "label_desc_fr": "FR Text",
        "label_desc_it": "IT Text",
        "label_desc_pt": "PT Text",
        "label_desc_cs": "CS Text"
    },
    "model": "myapp.labels",
    "pk": 2
}
]

So let's say I want to get the data from "label_desc_fr" WHERE label_number is 1 AND label_type = B. I tried to build and execute a QuerySet in my view like so:

q1 = labels.objects.filter(label_number="1")
q1 = q1.filter(label_type="B")

return render(request, 'frontend/base_home.html', {'q1' : q1})

The page loads without errors. Now I'm trying to access the data from my template like so:

{{q1.label_desc_fr}}

Nothing is shown. :( I searched for a way for a queryset to display all vars {{q1.?}} but I couldnt find a way to do this. The Django docs are, in my eyes, clear about creating QuerySets but not so mutch about how to retrieve them from a template. Now I'm wondering, how do I retrieve my results in my template?

Thanks guys!

Upvotes: 1

Views: 8836

Answers (1)

Gocht
Gocht

Reputation: 10256

Your problem is that you are accessing to q1 in template, and it is your complete QuerySet, it is not an single object. I think this should work:

q1 = labels.objects.filter(label_number="1", label_type="B")

return render(request, 'frontend/base_home.html', {'q1' : q1})

And then in your template:

{% for q in q1 %}

    {{ q.label_desc_fr }}

{% endfor %}

Upvotes: 2

Related Questions