2010-07-09 73 views
1

如何保证只有在相关对象都填充数据时才保存数据?如何保证两个相关模型得到保存?

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() 

我通过访问模型B中插入数据:

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

如果模型B中发生了错误,则模型甲仍然得到保存。 如何防止模型B在模型B未保存时保存?

回答

2

数据库事务?

0

覆盖B的保存方法(as described in the docs),有它调用的方法full_clean。如果引发异常,则不要保存模型。

+0

那么这不是问题。 如果B引发异常A仍然保存。 – rotrotrot 2010-07-09 11:30:19

+0

然后调用B的full_clean。 – 2010-07-09 11:53:17