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 开发者_Python百科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?
Depending on your environment, transactions are probably the answer
Database transactions?
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.
精彩评论