Monday, February 21, 2011

How to guarantee two related models get saved?

How do I guarantee data only gets saved when the related objects are both filled with data?

class A(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()

class B(A):
    author = models.CharField(max_length=255)
    url = models.URLField()

I insert data by accessing model B:

b = B()
b.title = 'title'
b.slug = 'slug'
b.author = 'author'
b.url = 'www.google.com'
b.save()

If an error occurs in model B then model A still gets saved. How can I prevent model A from saving when model B doesn't get saved?

From stackoverflow
  • Database transactions?

  • Depending on your environment, transactions are probably the answer

  • Override B's save method (as described in the docs), have it call A's full_clean method. if it raises an exception, just don't save the model.

    rotrotrot : Well that's not the problem. If B raises an exception A still gets saved.
    Ofri Raviv : Then call B's full_clean.

0 comments:

Post a Comment