如何使用Django进行“批量更新”?

编程入门 行业动态 更新时间:2024-10-28 02:33:31
本文介绍了如何使用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进行“批量更新”?

本文发布于:2023-10-23 22:22:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   批量   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!