简体   繁体   中英

how to use Django F() expression in `update` for JSONField

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.

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')
))

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