Search code examples
djangodjango-modelsjsonfield

Django - Merge jsonfield's new data with the old data


So let's assume that I have a model with a jsonfield while using Postgres as a database

class Baum(models.Model):
    myjson = models.JSONField(...)

Now I'd like to know what would be the best way to edit the model fields saving behaviour/interaction with the database

  1. myjson stores nested api responses, so dicts&lists
  2. When new data comes into myjson, dont delete/overwrite the old by calling save()
  3. -> Instead keep the old data and just add the new data, (if a func which proves that the data is new returns True)
  4. I need the data together, in one myjson field where from time to time pairs are coming on top of it. I am thankful for tips!

Solution

  • You can do:

    myBaum = Baum.objects.get()
    myBaum.myjson |= newdata  # dictionary update, Python 3.9+
    myBaum.save()