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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With