【发布时间】:2019-02-25 17:48:14
【问题描述】:
我正在尝试使用属性用户名和全名更新名为用户的对象;我的模型在下面。
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"] 从该页面获取值。
我的问题是如何更新整个对象,而无需在更新中指定特定属性,或者无需获取对象并设置我的新值并保存对象;我的观点如下。
def editUserByID(request, userID): if (request.method == "POST"): if (request.POST["userID"] != '' and request.POST["fullname"] != '' and request.POST["username"] != ''): 用户 1 = 用户( pk=request.POST["userID"], 全名=request.POST["全名"], 用户名=request.POST[“用户名”] ) 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 完全陌生,因此非常感谢任何帮助。
【问题讨论】:
-
使用 Django 的一个非常重要的原因是:它带来了一个现有的身份验证/授权框架,该框架是任何用户的基础,包括登录和其他任何东西。您将使用 Django,因为您不想从头开始实现该表单。见docs.djangoproject.com/en/2.1/topics/auth/default
-
我以User为例,但是如果是汽车或船或类似的东西,是否可以在一行代码中更新整个对象(多个属性)?谢谢你的文档顺便说一句,一定会检查出来的。
-
“但必须再次获取现有对象” - 您不需要“再次获取它”。只需将其存储在一个变量中,更改其字段,然后随时保存即可。