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

泄露秘密 提交于 2019-12-20 17:35:48

问题


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

but I need to get it dynamically. Ideally it would be something like this

model._meta._fields()['location_x'].verbose_name

I've looked at a few things but I just can't find it.


回答1:


For Django < 1.10:

model._meta.get_field_by_name('location_x')[0].verbose_name



回答2:


model._meta.get_field('location_x').verbose_name




回答3:


For Django 1.11 and 2.0:

MyModel._meta.get_field('my_field_name').verbose_name

More info in the Django doc




回答4:


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

<django.utils.functional.__proxy__ object at 0x{SomeMemoryLocation}>

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.




回答5:


model._meta.get_field_by_name('location_x')[0].verbose_name



回答6:


If you want to iterate on all the fields you need to get the field:

for f in BotUser._meta.get_fields():
    if hasattr(f, 'verbose_name'):
        print(f.verbose_name)


来源:https://stackoverflow.com/questions/2429074/how-can-i-get-access-to-a-django-model-field-verbose-name-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!