Django parent class model instances missing associated child model

145 Views Asked by At

I have a few Django models like this:

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):
  ...

So the idea is that when we have a instance of type Parent, we can figure out the associated child class by using the class_type attribute and get an instance of the child class. This has been working fine for a number of years, but in the last few weeks I have been seeing intermittent errors where parent.get() throws an exception because there is no associated child class. The exact error message is "Parent has no child1". There is nowhere in the code where I am creating raw Parent instances. I upgraded Django from 1.3 to 1.6 in recent weeks, but I'm not sure how that would break this code.

I had an idea that perhaps a query was failing midway so the database was creating the Parent record without getting a chance to complete creating the Child record. So I wrapped the view that creates the Child classes with a @transaction.atomic, but that didn't seem to fix the problem.

This only happens occasionally, but when it does, it breaks my web app for users.

0

There are 0 best solutions below