2
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

Averin Maxim
  • 373
  • 4
  • 19

2 Answers2

4

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.

schillingt
  • 13,493
  • 2
  • 32
  • 34
0

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)
)
Averin Maxim
  • 373
  • 4
  • 19
  • This yields the same output: django.db.utils.ProgrammingError: can't adapt type 'dict' – xyz Jan 31 '19 at 18:10