6

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?

Anupam
  • 14,950
  • 19
  • 67
  • 94

1 Answers1

13

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.

doru
  • 9,022
  • 2
  • 33
  • 43
  • Thanks - yes, I saw it there too but was wondering why it wasn't in the main Field Options reference. Perhaps just a documentation bug then. – Anupam May 11 '17 at 03:54
  • @Anupam It seems this is the way to get the name. See [this old answer](http://stackoverflow.com/a/3106314/1418794) too. – doru May 11 '17 at 05:52
  • 1
    @Anupam yes, i think is a lack in documentation – doru May 11 '17 at 06:07