2010-07-09 80 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