简体   繁体   English

在Django中使用JSONField进行批量更新

[英]Bulk update with JSONField in Django

whens = [When(pk=x, then=_json['info'][str(x)]) for x in ids]
Clinics.objects.filter(pk__in=ids).update(
  info_json=Case(*whens, output_field=JSONField())
)

I want to perform bulk update using Case-When statements for JSONField(). 我想使用Case-When语句对JSONField()执行批量更新。 When I do this in a stupid cycle with save() on every iteration everithing works fine. 当我在一个愚蠢的循环中使用save()在每次迭代中执行此操作时,一切正常。 But code above writes me: django.db.utils.ProgrammingError: can't adapt type 'dict' saying about second line. 但是上面的代码写了我: django.db.utils.ProgrammingError: can't adapt type 'dict'说的第二行。 I also tried json.loads(), but it didn't work out. 我也尝试了json.loads(),但是没有成功。 What should I do to perform this multiple update? 我应该怎么做才能执行此多次更新?

I am using Python 3.6.3 and Django 1.11.16 我正在使用Python 3.6.3和Django 1.11.16

For the time being you're stuck iterating over the instances and updating them one at a time. 目前,您一直在遍历实例并一次更新一个实例。 However, Django 2.2 will introduce bulk_update() which will do what you want. 但是,Django 2.2将引入bulk_update()来实现您想要的功能。

Actually bulk_update is simple case-when with casting. 实际上,在进行转换时,bulk_update很简单。 Here is solution without migrating to Django 2.2 这是无需迁移到Django 2.2的解决方案

field_type = Clinic._meta.get_field('info_json')
whens = [When(pk=x, then=Value(_json['info'][str(x)], output_field=field_type) 
for x in ids]
Clinics.objects.filter(pk__in=ids).update(
  info_json=Cast(Case(*whens, output_field=field_type),output_field=field_type)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM