开发者

How to guarantee two related models get saved?

开发者 https://www.devze.com 2023-01-07 00:50 出处:网络
How do I guarantee data only gets saved when the related objects are both filled with data? class A(models.Model):

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消