10

I have a queryset in Django that calls Model.objects.values('item')... where 'item' is a Foreign Key.

class Words(models.Model):
  word = models.CharField()

class Frequency(models.Model):
  word = models.ForeignKey(Words)
  ...

So this returns the item id and displays as an id in the template. How do I show the actual item value in the template instead of the id?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
simi
  • 103
  • 1
  • 1
  • 5

1 Answers1

12

To refer properties of Foreign Key items, you should use '__' lookup notation in fields. MyModel.objects.values('item__prop1', 'item__prop2', ...) should work for you.

And you can print it in templates by referencing the property names like this, when the name of template variable for the result is values.

{% for v in values %}
    Prop1: {{ v.item__prop1 }}
    Prop2: {{ v.item__prop2 }}
    ...
{% endfor %}
Achimnol
  • 1,551
  • 3
  • 19
  • 31
  • 3
    Obviously Achimnoi was using 'prop1' as an example - you should do `Model.objects.values('word__word')` in the view and `{{ v.word__word }}` in the template. – Daniel Roseman Oct 21 '09 at 19:09
  • This seems a viable solution when you have a single model. However, in my case I have a list of models and each model has a list of FKs (actually a many-to-many relationship). But it seems that should not be a problem as the values are still FKs (point to IDs in another table). The view is also serializing the list of models to JSON. – IAbstract Nov 30 '15 at 14:33