Django:找出继承层次结构中的哪个表具有该字段

Posted

技术标签:

【中文标题】Django:找出继承层次结构中的哪个表具有该字段【英文标题】:Django: Finding out which table in inheritance hierarchy has the field 【发布时间】:2011-08-02 11:03:52 【问题描述】:

考虑以下示例:

class Base(models.Model):
    myfield = models.CharField()
class Derived(Base):
    pass

现在,基类和派生类将在数据库中拥有不同的表。

我的问题是如何找出myfield属于哪个表?

【问题讨论】:

我在搜索答案时发现了一些关于 Django 的文档:django-model-internals-reference.readthedocs.org/en/latest/… 【参考方案1】:

使用_meta.get_fields_with_model()方法:

for field, model in Derived._meta.get_fields_with_model():
    if field.name == 'myfield':
        model = model or Derived
        print 'myfield belongs to %s' % model._meta.db_table

【讨论】:

以上是关于Django:找出继承层次结构中的哪个表具有该字段的主要内容,如果未能解决你的问题,请参考以下文章