1

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

4
  • I would actually advise not to use a JSON field. Relational databases are not good with JSON, and if the data is structured, like is the case here, it is often not a good idea, especially since it turns the database in non-normal form 1: en.wikipedia.org/wiki/First_normal_form Commented Dec 7, 2023 at 17:12
  • Okay thanks, any suggestions? Commented Dec 7, 2023 at 17:24
  • A ManyToManyField? Commented Dec 7, 2023 at 19:22
  • Does this help? Commented Dec 8, 2023 at 18:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.