Is it somehow possible to judge from a field instance whether it has been defined in the base class (‘myBaseModel’) or in the sub class (‘myDerivedModel’).
Or other way round. Is it possible to get all non-inherited fields from a model instance?
For now I made my way to the field instance. Maybe the field instance has some meta information attached to it?
The setup:
class myBaseModel(models.Model):
baseField = models.CharField(max_length=30)
class Meta:
abstract = True
class myDerivedModel(myBaseModel):
subClassField = models.CharField(max_length=30)
The approach:
myModel = get_model('my_app_name', 'myDerivedModel')
defaultFields = myModel._meta.get_all_field_names()
for field in defaultFields:
fieldInstance = myModel._meta.get_field_by_name(field)
print fieldInstance[0]
This outputs subClassField and baseField. I m looking for the way to only output the subClassField.
from django/db/models/options.py
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.
"""
1 Answer