简体   繁体   中英

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. 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:

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:

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.

If these don't work and you're still uncertain, post you object instance model and foreign_key model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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