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

Django 更新现有记录或创建新记录,django,django-models,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

如果一个条目已经存在,我会尝试更新数据库,如果不创建一个新条目的话

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,“密钥“用户id”的重复条目“15”)


对于Django,您必须使用
get
来获取现有对象,而不是创建新对象,这就是您当前对
UserProfiles(user=request.user)
的调用

例如:

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

有关更多信息,请参见。

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

例如:

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

请参阅以了解更多信息。

首先,虽然确实可以通过这种方式手动处理表单,但使用Django处理表单的“正确方法”是使用。有了这句话

我假设您的
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
因为在这两种情况下,您只需创建一个新对象并设置
用户
位置
电子邮件
的值

一旦尝试保存此对象,就会出现错误

正确的方法是首先从数据库中获取对象:

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.

有关更多信息,请首先查看

,虽然确实可以通过这种方式手动处理表单,但使用Django处理表单的“正确方式”是使用。有了这句话

我假设您的
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
因为在这两种情况下,您只需创建一个新对象并设置
用户
位置
电子邮件
的值

一旦尝试保存此对象,就会出现错误

正确的方法是首先从数据库中获取对象:

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.
有关更多信息,请查看您可以使用更简单的方法。

您可以使用更简单的方法