2012-04-26 73 views
1

我試圖更新數據庫,如果一個條目已經存在,如果不創建一個新的。更新現有記錄或創建新的

def saveprofile(request): 
    location = request.POST['location'] 
    email = request.POST['email'] 
    if request.user.is_authenticated(): 
     userprofile = UserProfiles(user=request.user) 
     if userprofile: 
      userprofile.location=location 
      userprofile.email=email 
      userprofile.save() 
      return render_to_response('profile.html',{'pfields':userprofile}) 
     else: 
      userprofile = UserProfiles(user=request.user, location=location, email=email) 
      userprofile.save() 
      return render_to_response('profile.html',{'pfields':userprofile}) 

它拋出

(1062, 「關鍵 'user_ID的' 重複項 '十五'」)

回答

2

你必須使用get Django的獲取現有的而不是創建一個新對象,這是您撥打UserProfiles(user=request.user)目前正在執行的操作。

例如:

try: 
    userprofile = UserProfiles.objects.get(user=request.user) 
except DoesNotExist: 
    # create object here. 

更多信息參見this link

0

首先,雖然這是真的,但您可以用這種方式手動處理表單,但使用Django執行表單的「正確方法」是使用django.forms。有了這個說...

我假設你的UserProfiles模型不包含明確的主鍵。這意味着,Django會自動創建自己的字段,稱爲id

現在,當您使用構造函數創建模型的新實例時,id字段將保持爲空。它不會從數據庫中獲取任何東西,它會創建一個新的對象。之後,您可以爲其字段分配一些值。需要注意的是以下兩者是等價的:

userprofile = UserProfiles(user=request.user, location=location, email=email) 

# and 
userprofile = UserProfiles(user=request.user) 
userprofile.location=location 
userprofile.email=email 

因爲在這兩種情況下,你只需要創建一個新的對象,並設置userlocationemail值。

只要您嘗試保存此對象,就會出現錯誤。

做到這一點,正確的方法是,首先從數據庫中獲取對象:

try: 
    profile = UserProfiles.objects.get(user=request.user) 
except DoesNotExist: 
    # Handle the case where a new object is needed. 
else: 
    # Handle the case where you need to update an existing object. 

欲瞭解更多信息,看看https://docs.djangoproject.com/en/dev/topics/db/queries/

3

您可以使用get_or_create這是要簡單得多。

+1

斷開的鏈接。如果可能,請更新。 – 2016-12-10 00:56:58

相關問題