I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible?
I can load the model dynamically:
from django.db import models
model = models.get_model('myapp','mymodel')
Now I have field - 'myfield' - how can I get the class of that field?
If the field is relational - how to get related field?
Thanks a bunch!
If you would like to see ALL fields on a Django model object you can simply introspect it by calling
._meta.get_fields()
on the class (or an instantiated model object) to get at list of all fields. This API is current with the latest version of Django.Example:
This will return a tuple of all model fields. Documentation can be found HERE.
You can use model's
_meta
attribute to get field object and from field you can get relationship and much more e.g. consider a employee table which has a foreign key to a department tablefrom django/db/models/options.py
The answer from Anurag Uniyal to use
get_field_by_name
is now (5 years later) outdated asget_field_by_name
is deprecated. Django will give you the following hint:API docs for
get_field
are here.django.db.models.loading.get_model() has been removed in django 1.9. You are supposed to use django.apps instead.
'get_field_by_name is an unofficial API that has been deprecated in Django 1.10. You may be able to replace it with 'get_field()'
link to issue