简体   繁体   English

Django - 需要 get_FOO_display 用于表单中的外部字段

[英]Django - need a get_FOO_display for a foreign field in a form

I've got a form template, to which I'm passing the form info as well as the object itself.我有一个表单模板,我将表单信息以及 object 本身传递给该模板。 I can use {{ object.get_FOO_display }} no problem for choice fields when the choice field is a part of the object itself, but I'm looking for an easy way to do the same for the foreign fields that are in the form. I can use {{ object.get_FOO_display }} no problem for choice fields when the choice field is a part of the object itself, but I'm looking for an easy way to do the same for the foreign fields that are in the form.

I'm building this into a class-based view, so ideally any suggestions could be coded independent of references to specific fields.我将其构建为基于类的视图,因此理想情况下,任何建议都可以独立于对特定字段的引用进行编码。

Thanks!谢谢!

If I'm not mistaken and you are trying to get display value for a django model instance with a choices attribute, you could simply:如果我没记错,并且您正在尝试获取具有选择属性的 django model 实例的显示值,您可以简单地:

object.foreign_key_field.get_FOO_display

However, if you are working backwards (ie trying to get display value for a model instance that has a foreign key pointing to your object instances model and a related_name attribute of fk_related_name) then:但是,如果您正在向后工作(即尝试获取 model 实例的显示值,该实例具有指向您的 object 实例 model 的相关名称属性,然后是相关名称属性)

object.fk_related_name.get_query_set()[i].get_FOO_display

get_query_set returns a queryset, so you could either iterate over the queryset with a {% forloop %} or provide the index [i] of the object you want, as above. get_query_set 返回一个查询集,因此您可以使用 {% forloop %} 遍历查询集或提供您想要的 object 的索引 [i],如上所述。

If these don't work and you're still uncertain, post you object instance model and foreign_key model.如果这些不起作用并且您仍然不确定,请发布您的 object 实例 model 和 foreign_key model。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM