在外键上将Django values()显示在模板中作为对象而不是其id [英] Display Django values() on Foreign Key in template as object instead of its id

查看:625
本文介绍了在外键上将Django values()显示在模板中作为对象而不是其id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有一个查询器,调用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆