如何在Django中更新模型对象? [英] How to update model object in django?
问题描述
我正在使用以下代码更新状态。
I am using below code for update the status.
current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id')
current_challenge.update(status=str(request.data['status']))
我遇到以下错误:
'UserChallengeSummary'对象没有属性'update'
'UserChallengeSummary' object has no attribute 'update'
要解决此错误:
我找到了解决方案:
For solve this error: I found solutions:
current_challenge.status = str(request.data['status'])
current_challenge.save()
还有其他更新记录的方法吗?
Is there any another way to update record?
推荐答案
您的工作解决方案是通常使用的方法
Your working solution is the way usually used in Django, as @Compadre already said.
但是有时候(例如,在测试中)能够一次更新多个字段很有用。对于这种情况,我编写了简单的帮助程序:
But sometimes (for example, in tests) it's useful to be able to update multiple fields at once. For such cases I've written simple helper:
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()
从函数(在函数调用后显式调用)。
If you with, you can remove instance.save()
from the function (to call it explicit after the function call).
这篇关于如何在Django中更新模型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!