简体   繁体   中英

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(). When I do this in a stupid cycle with save() on every iteration everithing works fine. But code above writes me: django.db.utils.ProgrammingError: can't adapt type 'dict' saying about second line. I also tried json.loads(), but it didn't work out. What should I do to perform this multiple update?

I am using Python 3.6.3 and 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.

Actually bulk_update is simple case-when with casting. Here is solution without migrating to 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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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