views:

51

answers:

3

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?

+2  A: 

Database transactions?

Messa
+3  A: 

Depending on your environment, transactions are probably the answer

pycruft
A: 

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.

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