[Fixed]-Append JSON array with another item using Python

2👍

model.fruits = {"id": 1, "name": "apple"}* defines a dictionary, you cannot append to a dictionary, you can add keys to it

You can append elements into a JSON array though, e.g. if model.fruits was an array (or a list, as it is called in Python), e.g.

model.fruits = [{"id": 1, "name": "apple"},]

which defines an array with 1 element in it, then you can append to it

model.fruits.append({"id": 2, "name": "banana"})

Some references:

https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#hstorefield
https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#arrayfield

* To be honest it doesn’t make sense to name something in the plural like fruits to hold a single object, should be a container, like a list

👤bakkal

-1👍

In Django, you should make a new model called Fruit.

class Fruit(models.Model):
    name = models.Charfield(max_length=50)

in your main model you should have a ManyToManyField.

fruits = models.ManyToManyField(Fruit, blank=True, related_name='model')

This way you would be able to add some more fields in future do filtering and whole other things.

To add a fruit to model object

obj.fruits.add(1, 2)  # where 1 and 2 are id's  of fruits to add

Leave a comment