Home > front end >  how to use Django F() expression in `update` for JSONField
how to use Django F() expression in `update` for JSONField

Time:05-21

I have around 12 million records that I need to update in my postgres db (so I need to do it in an efficient way). I am using Django.

I have to update a jsonfield column (extra_info) to use values from a different column (related_type_id which is an integer) in the same model.

Trying to do it with an update. This seems to be the way to do it most efficiently. Example:

Person.objects.all().update(extra_info={
  "type": "Human",
  "id": F('related_type_id')
})

This errors out with : "Object of type F is not JSON serializable". I thought the F() will give back the value of that column (which should be an integer) which should be serializable. Can this be done ? Or am I trying to do it in the wrong way. I don't really want to iterate in a for loop and update each record with a save() because it will take too long. There's too many records.

CodePudding user response:

The Django database function JSONObject should work, it returns a valid JSON object from key-value pairs and may be passed F objects

from django.db.models import F, Value
from django.db.models.functions import JSONObject

Person.objects.all().update(extra_info=JSONObject(
  type=Value('Human'),
  id=F('related_type_id')
))
  • Related