Display Django values() on Foreign Key in template as object instead of its id

我的梦境 提交于 2020-01-12 14:24:09

问题


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?


回答1:


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 %}


来源:https://stackoverflow.com/questions/1602557/display-django-values-on-foreign-key-in-template-as-object-instead-of-its-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!