Django父类模型实例缺少关联的子模型

时间:2014-01-18 16:11:17

标签: django django-models django-inheritance

我有几个像这样的Django模型:

CLASS_TYPE_CHOICES = (('type1', 'Type 1'), ('type2', 'Type 2'))

class Parent(models.Model):
  class_type = models.CharField(max_length=10, choices=CLASS_TYPE_CHOICES)

  def get(self):
    if self.class_type == 'type1':
      return self.child1
    elif self.class_type == 'type2':
      return self.child2
    else:
      return self

class Child1(Parent):
  ...

class Child2(Parent):
  ...

所以我们的想法是,当我们有一个Parent类型的实例时,我们可以通过使用class_type属性找出关联的子类,并获取子类的实例。多年来一直运行良好,但在过去的几周里,我一直看到间歇性错误,其中parent.get()抛出异常,因为没有关联的子类。确切的错误消息是“Parent has no child1”。代码中没有任何地方我在创建原始Parent实例。最近几周我将Django从1.3升级到1.6,但我不确定这会如何破坏这段代码。

我有一个想法,也许一个查询中途失败,所以数据库正在创建父记录而没有机会完成创建子记录。所以我用@ transaction.atomic包装创建Child类的视图,但这似乎没有解决问题。

这种情况偶尔会发生,但一旦发生,就会破坏用户的网络应用。

0 个答案:

没有答案
相关问题