Django1.4,继承 - 在子类中确定字段是从父类继承还是在子类中定义

时间:2012-08-21 13:17:37

标签: django inheritance django-models

是否有可能从字段实例判断它是否已在基类('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.
    """

1 个答案:

答案 0 :(得分:1)

inherited_fields=[]
for base_class in list(myModel .__bases__):
    inherited_fields.extend(base_class._meta.get_all_field_names())
... your code
for field in defaultFields:
    if field not in inherited_fields:
        do_something_with_non_inherited_fields()