Rk..
Rk..

Reputation: 753

Making queries for a single row table in Django

This may be a simple one. But I could not reason it out. I am using Django 1.7.2

I have a model where there is only one row of data in the table.

Case 1 : objects.all()

info = ModelName.objects.all()

I get the data but when I try to put it in a template, it is not getting displayed.

{% for item in info %}
    {{ item.name }}
{% endfor %}

Case 2 : objects.get()

info = ModelName.objects.get()

I get the data and it is getting displayed in template.

{{ info.name }}

Questions:

Could anyone explain why case 1 is not working?

And in case 2 using get() without any pk value is fine?

Upvotes: 0

Views: 611

Answers (1)

Sten Wessel
Sten Wessel

Reputation: 195

Case 2 works fine, because the arguments for the get() function are optional. If you don't provide anything, it will match against every record. Since you table only has one, it raises no exception.

See the docs: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#get

Your case 1 should be working, though. Check if your info is in your context for the template.

Upvotes: 1

Related Questions