本文介绍了如何使用Django进行“批量更新”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
更新tbl_name set name = 'foo'其中name ='bar'
我的第一个结果是这样的 - 但这是讨厌的,不是吗?
list = ModelClass.objects.filter(name ='bar') for obj列表: obj.name ='foo' obj.save()有更优雅的方式吗?
解决方案请参阅更新在django文档中的功能: docs.djangoproject/en /1.9/ref/models/querysets/#update 。
简而言之,您应该可以使用:
ModelClass。 object.filter(name ='bar')。update(name =foo)也可以使用 F 对象来执行增加行的事情:
from django .db.models import F Entry.objects.all()。update(n_pingbacks = F('n_pingbacks')+ 1)请参阅文档: https:// docs.djangoproject/en/1.9/topics/db/queries/
但是请注意:
- 这不会使用 ModelClass.save 方法(所以如果你有一些逻辑不会被触发)。
- 不会发出django信号。
I'd like to update a table with Django - something like this in raw SQL:
update tbl_name set name = 'foo' where name = 'bar'My first result is something like this - but that's nasty, isn't it?
list = ModelClass.objects.filter(name = 'bar') for obj in list: obj.name = 'foo' obj.save()Is there a more elegant way?
解决方案Refer to the update function in django documentation: docs.djangoproject/en/1.9/ref/models/querysets/#update.
In short you should be able to use:
ModelClass.objects.filter(name='bar').update(name="foo")You can also use F objects to do things like incrementing rows:
from django.db.models import F Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)See the documentation: docs.djangoproject/en/1.9/topics/db/queries/
However, note that:
- This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
- No django signals will be emitted.
更多推荐
如何使用Django进行“批量更新”?
发布评论