Reputation: 253
I have a database with tags for an image gallery. They contain the fields 'id', 'picture_id' and 'tag'. I am trying to build a list of all tags, but without listing the same tag twice. This I know I can do with distinct() in the queryset, but using this with all() only throws an error telling me that backend database does not support it. (I'm using MySQL).
If I use values_list('id','tag') I don't get that error. I don't get any error at all actually. But I don't get anything I can print out in my template either.
The queryset is written like this:
tags = Tag.objects.values_list('id', 'tag').distinct().order_by('tag')
In template I can try to print this with:
{% for tag in tags %}
<p>{{ tag.id }}: {{ tag.tag }}</p>
{% endfor %}
This gives me a long(ish) row of ':' signs, but nothing on its right or left side. This indicates to me that there are stuff in my list, but I can't seem to use it. What am I doing wrong?
EDIT: It's worth noting that I tried doing these things in a Shell and when printing out tags there I get a list of objects that seemingly consists of both id and tag, but I still can't seem to get it output in template.
Upvotes: 0
Views: 1107
Reputation: 53998
values_list
will create a list of tuples, not dictionaries, so using dictionary notation won't work. Check out the the docs:
... instead of returning a list of dictionaries, it returns a list of tuples. Each tuple contains the value from the respective field passed into the values_list() call -- so the first item is the first field, etc. For example:
>> Entry.objects.values_list('id', 'headline')
[(1, u'First entry'), ...]
So, instead you should do :
{% for tag in tags %}
<p>{{ tag.0 }}: {{ tag.1 }}</p>
{% endfor %}
Upvotes: 2