Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get field's name from Field object

I am trying to find out the recommended way of getting a model field's name from a Field object.

It seems field.name works (which I found out from some SO posts) if field is the object name but surprisingly its not mentioned anywhere in the docs, so want to know if its still the best way or am I missing something obvious?

like image 346
Anupam Avatar asked May 10 '17 15:05

Anupam


1 Answers

It seems this is the right way to get the model field's name. field.name is also used in docs (see at the bottom of the page) when explaining the migration from the old API to the new model _meta API:

MyModel._meta.get_all_field_names() becomes:

from itertools import chain
list(set(chain.from_iterable(
    (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
    for field in MyModel._meta.get_fields()
    # For complete backwards compatibility, you may want to exclude
    # GenericForeignKey from the results.
    if not (field.many_to_one and field.related_model is None)
)))

and

[f.name for f in MyModel._meta.get_fields()] 

Also it feels logically to be so because, on the other hand, when you want a field object you can get it by its name:

f = MyModel._meta.get_field(name)

so f.name will be the name of the field.

like image 193
doru Avatar answered Nov 11 '22 11:11

doru