如何在Django中更新模型对象?

2024-10-01 15:44:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的代码更新状态。在

current_challenge = UserChallengeSummary.objects.filter(user_challenge_id=user_challenge_id).latest('id')
current_challenge.update(status=str(request.data['status']))

我得到以下错误:

'UserChallengeSummary' object has no attribute 'update'

要解决此错误: 我找到了解决方案:

^{pr2}$

有没有其他方法更新记录?在


Tags: 代码idobjectsrequest状态status错误update
2条回答

latest()方法返回最新对象,该对象是UserChallengeSummary的实例,它没有更新方法。在

对于更新单个对象,您的方法是标准的。在

update()方法用于一次更新多个对象,因此它适用于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)

使用示例:

^{pr2}$

如果使用,则可以从函数中移除instance.save()(在函数调用后显式调用)。在

相关问题 更多 >

    热门问题