Django使用proxys对复杂的继承进行建模



我有这些型号:

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()自动下转换的属性。

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

根据文档,Queryset仍然返回请求的模型。参见此处

在您的示例中,您为原始模型Base返回一个Queryset。

最新更新