2012-04-26 76 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

相关问题