如何更新 django 中的模型对象?

Soh*_*iya 5 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']))
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

“UserChallengeSummary”对象没有属性“update”

为了解决这个错误:我找到了解决方案:

current_challenge.status = str(request.data['status'])
current_challenge.save()
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以更新记录吗?

Igo*_*kiy 6

正如 @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)
Run Code Online (Sandbox Code Playgroud)

使用示例:

current_challenge = update_attrs(current_challenge, 
                                 status=str(request.data['status']),
                                 other_field=other_value)
                                 # ... etc.
Run Code Online (Sandbox Code Playgroud)

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


kha*_*vah 0

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

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

update()方法用于一次更新多个对象,因此它适用于QuerySet实例。