【问题标题】:How to update model object in django?如何在 django 中更新模型对象?
【发布时间】:2016-12-18 02:05:30
【问题描述】:

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

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

我遇到以下错误:

“UserChallengeSummary”对象没有“更新”属性

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

current_challenge.status = str(request.data['status'])
current_challenge.save()

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

【问题讨论】:

  • 据我所知,你的解决方案对于 django 来说很普通

标签: python django django-models


【解决方案1】:

正如@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 方法来更新模型——使用起来非常好。我使用上面提供的代码只是为了让我的单元测试更短。
  • 是的,我们可以使用原始查询。但是如果我们可以使用 ORM 查询就很容易了。
  • @Soham Navadiya:通过“原始”Django 方式,我的意思是 ORM 调用您在帖子中提供,而不是原始 SQL!
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2018-08-18
    • 2016-03-10
    • 2018-01-14
    • 1970-01-01
    • 2017-12-13
    • 2014-05-05
    相关资源
    最近更新 更多