Search code examples
pythondjangopostgresqldjango-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(). 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


Solution

  • 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.