在外键上将Django values()显示在模板中作为对象而不是其id [英] Display Django values() on Foreign Key in template as object instead of its id
问题描述
Model.objects.values('item')
...其中'item'
是外键。 class Words(models.Model):
word = models.CharField()
class Frequency(models.Model):
word = models.ForeignKey(Words)
...
所以这样返回项目ID,并在模板中显示为一个id。
要引用外键项的属性,您可以应在字段中使用'__'查找符号。 MyModel.objects.values('item__prop1','item__prop2',...)
应该适合你。
您可以通过引用属性名称在模板中打印,当结果的模板变量的名称为值
。
{%for value in $%
Prop1:{{v.item__prop1}}
Prop2:{{v.item__prop2}}
...
{%endfor%}
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?
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 %}
这篇关于在外键上将Django values()显示在模板中作为对象而不是其id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!