1

I have a Photo class which inherits from Content model like this:

class Content(models.Model):
    added = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Photo(Content):
    file = models.ImageField(upload_to='photos/')

    def __unicode__(self):
        return self.caption and self.caption or ''

As can be seen, Content itself is not abstract. By a ModelForm, I am uploading photos. But, if saving of the Photo fails for some reason, an orphan Content instance is left. I guess the instance for the parent model is created before the Photo instance is saved but if photo fails, the parent is not cleaned-up.

Is this a bug on Django side? How can this be prevented?

onurmatik
  • 5,105
  • 7
  • 42
  • 67
  • 1
    Since `Content` is not abstract, it gets its own table. `Photo` is a separate table with a hidden `OneToOneField` pointing at the associated `Content`. Thus the `Content` entry needs to be generated first since its `id` field is needed to create the `Photo` entry. Since you'll want the `Content` rolled back if the `Photo` can't be created, you ned transactions (see below). – Mike DeSimone Jul 03 '11 at 14:59
  • thanks, i will. but i think this is something to be handled by django similar to how its database abstraction provides consistency checks in other cases like foreign keys. – onurmatik Jul 03 '11 at 15:50
  • Django doesn't provide ForeignKey consistency checks, IIRC; the database does that. I get lots of warnings whenever I use SQLite that the FK constraints generated by Django are being ignored. In the case of transactions, they are too complex an action for Django to have any decent chance of inferring their proper use, so it must be punted to the developer. – Mike DeSimone Jul 03 '11 at 17:09

1 Answers1

3

Same as always. Use transactions.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358