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 it开发者_Python百科self. 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.
精彩评论