是否有可能从字段实例中判断它是在基类('myBaseModel')还是在子类('myDerivedModel')中定义的。
或者其他方式。是否可以从模型实例中获取所有非继承字段?
现在我来到了现场实例。也许字段实例附加了一些元信息?
设置:
class myBaseModel(models.Model):
baseField = models.CharField(max_length=30)
class Meta:
abstract = True
class myDerivedModel(myBaseModel):
subClassField = models.CharField(max_length=30)
该方法:
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]
这将输出 subClassField 和 baseField。我正在寻找只输出 subClassField 的方法。
来自 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.
"""