Django更新整个对象(行)

时间:2018-09-21 10:25:21

标签: python django

我正在尝试使用用户名和全名属性更新名为User的对象;我的模特在下面。

class User(models.Model):
"""docstring for User"""

fullname = models.TextField()
username = models.TextField()
password = models.TextField()
createdDate = models.DateTimeField(default=timezone.now)
publishedDate = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.publishedDate = timezone.now
    self.save()

def __str__(self):
    return str("\npk= " + self.pk + " | fullname= " + self.fullname + " | username= " + self.username + "\n")

我已经创建了一个编辑页面,并且能够通过request.POST [“ fullname”]和request.POST [“ username”]从该页面中获取值。

我的问题是,如何更新整个对象,而不必在update中指定特定的属性,或者不获取对象并设置新值并保存对象;我的看法在下面。

def editUserByID(request, userID):
    if (request.method == "POST"):
        if (request.POST["userID"] != '' and request.POST["fullname"] != '' and request.POST["username"] != ''):
            user1 = User(
                pk=request.POST["userID"],
                fullname=request.POST["fullname"],
                username=request.POST["username"]
            )

print(user1) # this only updates 1 property, so for multiple properties I would have to write multiple statements User.objects.filter(pk=user1.pk).update(fullname=user1.fullname) # is this possible? send the entire object and have it update the DB User.objects.filter(pk=user1.pk).update(user1) # this is how I was able to save it, but have to get the existing object again, assign the new values and then save updateUser = User.objects.get(pk=user1.pk) updateUser.fullname=user1.fullname updateUser.username=user1.username updateUser.save() else: user2 = User.objects.get(pk=userID) return render (request, 'helloworld/editUser.html', {'user': user2}) return redirect('listUsers')

PS:到目前为止,我一直在使用Java和.NET,但是对于Python / Django来说是全新的,所以我们将不胜感激。

2 个答案:

答案 0 :(得分:2)

这主要是错误的方法。首先,无需创建var jsonObject = JSON.stringify({ "api_key":"8a661f60-5873-11e5-a4c8-7f9bc5b8cb08" }); var postheaders = { 'content-Type':'application/json', 'content-Length':Buffer.byteLength(jsonObject,'utf8') // "api_key":"8a661f60-5873-11e5-a4c8-7f9bc5b8cb08" }; var optionspost = { host:'config.remote.host', port:'config.remote.port', path:'api/get_all_domains', method:'POST', headers:postheaders }; console.info('Options prepared:'); console.info(optionspost); console.info('Do the POST call'); var reqPost = https.request(optionspost, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { console.info('POST result:\n'); process.stdout.write(d); console.info('\n\nPOST completed'); }); }); reqPost.write(jsonObject); reqPost.end(); reqPost.on('error', function(e) { console.error(e); }); ;如果要更新现有对象,则应直接在此处设置值。

但是在Django中执行此操作的方法是使用ModelForm。这样做有很多优点,特别是它将验证您的输入,检查是否已提供所有必填字段以及它们的类型正确。您可以在实例化表单时将现有用户作为user1参数传递,然后在保存表单时更新该实例。

instance

此外,我赞成Risadinha的观点,即您不应创建自己的用户模型。使用Django的内置身份验证框架。

答案 1 :(得分:0)

您可以像这样在一行中完成此操作:

User.objects.filter(pk=user1.pk).update(fullname=user1.fullname, 
username=user1.username) 

更新模型的另一种方法是使用如下形式:

# You can get user based on your logic
user = request.user
# 'EditUserForm' is the custom form, read more about django model forms if you already have not, https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method
user_form = EditUserForm(request.POST, instance=user)
if user_form.is_valid():
    user_form.save()
else:
    user2 = User.objects.get(pk=userID)
    return render (request, 'helloworld/editUser.html', {'user': user2})

return redirect('listUsers')