更新现有记录或创建新记录

时间:2012-04-26 16:37:34

标签: django django-models

如果没有创建新条目,我正在尝试更新数据库。

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'的重复条目'15'”

3 个答案:

答案 0 :(得分:3)

您可以使用更简单的get_or_create

答案 1 :(得分:2)

您必须使用get让Django获取现有对象而不是创建新对象,这是您对UserProfiles(user=request.user)的调用当前正在进行的操作。

例如:

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

有关详细信息,请参阅this link

答案 2 :(得分:0)

首先,虽然确实可以手动处理表单,但使用Django表单的“正确方法”是使用django.forms。这说了......

我假设您的UserProfiles模型不包含显式主键。这意味着,Django会自动创建自己的字段,称为id

现在,当您使用构造函数创建模型的新实例时,id字段将保持为空。它不会从dabase中获取任何内容,它会创建一个新对象。然后,为其字段分配一些值。请注意,以下两个是等效的:

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/