I'm trying to efficiently append a value to a JSONField (hobbies) in a Django model using the update_or_create method. I know it is easy to do this by initially calling the update_or_create method, then I get the hobbies field, append the information and the save again.
However, I want to avoid hitting the database twice. I tried using the F() expression but I'm getting django.db.utils.OperationalError: (3156, 'Invalid JSON value for CAST to DOUBLE from column history at row 1')
Here's the relevant code snippet:
# models.py
class UserProfile(models.Model):
...
hobbies = models.JSONField(default=list)
The code below is quite straight forward but I want to avoid hitting the DB twice
user_profile, created = UserProfile.objects.update_or_create(user=user)
user_profile.hobbies.append("Music")
user_profile.save()
I want to perform this action at a go so I tried the code below but it is raising django.db.utils.OperationalError: (3156, 'Invalid JSON value for CAST to DOUBLE from column history at row 1').
user_profile, created = UserProfile.objects.update_or_create(
user=user,
defaults={
"hobbies": F("hobbies") + ["Music"]
}
)
I would really appreciate any help. Thanks
ManyToManyField?