Django get field's name from Field object

12,812

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.

Share:
12,812
Anupam
Author by

Anupam

Social Entrepreneur. CTO at Saathi Re (https://www.saathire.com) Work at intersection of technology and social impact Part of the exclusive network at CodementorX.

Updated on July 03, 2022

Comments

  • Anupam
    Anupam almost 2 years

    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?