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')
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 table
In : from django.db import models In : model = models.get_model('timeapp', 'Employee') In : dep_field = model._meta.get_field_by_name('department') In : dep_field.rel.field_name Out: 'id' In : dep_field.rel.to Out: <class 'timesite.timeapp.models.Department'>
def get_field_by_name(self, name): """ Returns the (field_object, model, direct, m2m), where field_object is the Field instance for the given name, model is the model containing this field (None for local fields), direct is True if the field exists on this model, and m2m is True for many-to-many relations. When 'direct' is False, 'field_object' is the corresponding RelatedObject for this field (since the field doesn't have an instance associated with it). Uses a cache internally, so after the first access, this is very fast. """