python - 从数据库重新加载 django 对象

标签 python django django-models

是否可以从数据库中刷新 django 对象的状态?我的意思是行为大致相当于:

new_self = self.__class__.objects.get(pk=self.pk)
for each field of the record:
    setattr(self, field, getattr(new_self, field))

更新:在跟踪器中发现了重新打开/不会修复 war :http://code.djangoproject.com/ticket/901 . 还是不明白为什么维护者不喜欢这个。

最佳答案

从 Django 1.8 开始,内置刷新对象。Link to docs .

def test_update_result(self):
    obj = MyModel.objects.create(val=1)
    MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
    # At this point obj.val is still 1, but the value in the database
    # was updated to 2. The object's updated value needs to be reloaded
    # from the database.
    obj.refresh_from_db()
    self.assertEqual(obj.val, 2)

关于python - 从数据库重新加载 django 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377861/

相关文章:

python - 在Python的列表中搜索包含 "<"和 ">"的值

node.js - 将 Nginx 设置为 Nodejs 和 Django 的代理

mysql - 无法让 MySQL/MariaDB 在 Fedora 24 上与 Django 1.10.1 和 Python 3.5 配合使用?

django-models - django 更新模型不影响 auto_now 时间戳

python - 在 django-profile 中添加字段 first_name 和 last_name

python - 调用后python中的声明函数

python - ctypes中的编译器依赖

python - Django 线程评论系统

python - Django cache_page 检查

django: sqlite3.OperationalError: 没有这样的表