【问题标题】:Django models complex inheritance with proxysDjango 使用代理对复杂继承进行建模
【发布时间】:2012-08-28 14:24:29
【问题描述】:

我有这些模型:

class Base(models.Model):
    # ... attributes
    def f(self):
        raise Exception()

class A(Base):
    attribute = models.IntegerField()

class B(A):
    class Meta:
        proxy = True
    def f(self):
        print "B", attribute

class C(A):
    class Meta:
        proxy = True
    def f(self):
        print "C", attribute

现在我和他们玩了一下,但我发现了一个问题:

c = C()
c.attribute = 1
c.save()

b = Base.objects.all()
b.f() # Aspected "C 1" to be printed, exception fired instead!

最后一行以意想不到的方式工作!因此,为了更好地查看文档,我搜索了 Django 自动向下转换属性,但我只找到了 A() 类中的一个,该类对于 B()C() 都没有自动转换。

当我保存数据时,还有一种方法可以保存继承吗? 谢谢!

【问题讨论】:

    标签: python django django-models django-inheritance


    【解决方案1】:

    根据文档,查询集仍会返回请求的模型。见here

    在您的示例中,您返回原始模型 Base 的查询集。

    【讨论】:

    • 谢谢,但无论如何有一种方法可以识别出什么样的对象并投射到它?
    猜你喜欢
    • 2023-03-06
    • 2013-04-08
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2021-06-08
    • 2019-06-22
    相关资源
    最近更新 更多