Python 如何在django中更新模型对象?
我使用下面的代码更新状态Python 如何在django中更新模型对象?,python,django,django-models,Python,Django,Django Models,我使用下面的代码更新状态 current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id') current_challenge.update(status=str(request.data['status'])) 我得到以下错误: “UserChallengeSummary”对象没有“update”属性 要解决此错误,请执行以下操作: 我找到了解决办
current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id')
current_challenge.update(status=str(request.data['status']))
我得到以下错误:
“UserChallengeSummary”对象没有“update”属性
要解决此错误,请执行以下操作:
我找到了解决办法:
current_challenge.status = str(request.data['status'])
current_challenge.save()
是否有其他方法更新记录?方法返回最新的对象,该对象是没有更新方法的UserChallengeSummary
的实例
对于更新单个对象,您的方法是标准的
方法用于一次更新多个对象,因此它适用于
QuerySet
实例。正如@Compadre所说,您的工作解决方案是Django中通常使用的方法
但有时(例如,在测试中),能够同时更新多个字段是很有用的。对于这种情况,我编写了简单助手:
def update_attrs(instance, **kwargs):
""" Updates model instance attributes and saves the instance
:param instance: any Model instance
:param kwargs: dict with attributes
:return: updated instance, reloaded from database
"""
instance_pk = instance.pk
for key, value in kwargs.items():
if hasattr(instance, key):
setattr(instance, key, value)
else:
raise KeyError("Failed to update non existing attribute {}.{}".format(
instance.__class__.__name__, key
))
instance.save(force_update=True)
return instance.__class__.objects.get(pk=instance_pk)
用法示例:
current_challenge = update_attrs(current_challenge,
status=str(request.data['status']),
other_field=other_value)
# ... etc.
如果使用,可以从函数中删除
instance.save()
(在函数调用后显式调用) 据我所知,您的解决方案对Django来说很普通,谢谢您的快速回复。我肯定会用你的解决方案来解决我的问题。我建议你再看看“原始”Django更新模型的方法——使用它很好。我使用上面提供的代码只是为了缩短我的单元测试。是的,我们可以使用原始查询。但如果我们可以使用ORM查询来实现,那就很容易了。@Soham Navadiya:我所说的“原始”Django方式是指您在文章中提供的ORM调用,而不是原始SQL!