How can I get access to a Django Model field verbose name dynamically?

后端 未结 6 728
陌清茗
陌清茗 2021-02-06 22:12

I\'d like to have access to one my model field verbose_name.

I can get it by the field indice like this

model._meta._fields()[2].verbose_name

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 22:53

    The selected answer gives a proxy object which might look as below.

    
    

    If anyone is seeing the same, you can find the string for the verbose name in the title() member function of the proxy object.

    model._meta.get_field_by_name(header)[0].verbose_name.title()
    

    A better way to write this would be:

    model._meta.get_field(header).verbose_name.title()
    

    where header will be the name of the field you are interested in. i.e., 'location-x' in OPs context.

    NOTE: Developers of Django also feel that using get_field is better and thus have depreciated get_field_by_name in Django 1.10. Thus I would suggest using get_field no matter what version of Django you use.

提交回复
热议问题