2009-11-20 41 views
2

我在,我在我的項目中使用一個基於Django的應用程序中發現一個模糊的地方,請看看這個:關於在Django分組SQL查詢...

if not request.method == 'POST' or not request.POST.get('openid'): 
    raise RedirectException(next, _('Invalid POST data')) 
if not UserAssociation.objects.filter(user=request.user).count() > 1 and not request.user.email: 
    raise RedirectException(next, _("You must have at least one OpenID if you don't have email!")) 
try: 
    ua = UserAssociation.objects.get(openid_url=request.POST['openid'], user=request.user) 
    ua.delete() 
except UserAssociation.DoesNotExist: 
    pass 

作者試圖實現至少一個紀錄表UserAssociation用於沒有電子郵件的用戶。但是檢查記錄計數和後續擦除操作不是原子一體的。因此,我們無法確定在調用delete()方法的時候,我們仍然有更多的1個用戶在該表的記錄。

是否有解決類似問題的最佳做法?

回答

1

在這種情況下,很容易:只需在已過濾的查詢集上使用delete()而不是get()

UserAssociation.objects.filter(openid_url=request.POST['openid'], user=request.user).delete() 

在其他情況下,通常它可以幫助將SQL調用包裝在單個數據庫事務中。有關說明,請閱讀官方transaction docs