0

I recently migrated to Python and cannot solve quite simple problem (using Django). A model has JSON field (PostgreSQL), lets say, for example, fruits. When updating an instance, I do it like this:

model.fruits = {"id": 1, "name": "apple"}
model.save()

When editing a model, I would like to add another fruit (append), so the result would have few JSON items, and model.fruits would return value like this:

[
    {
        "id": 1,
        "name": "apple"
    },
    {
        "id": 2,
        "name": "banana"
    },
    {
        "id": 3,
        "name": "orange"
    },
]

I have tried to search for solutions, but it seems like append function for this dictionary overwrites the values, not appends them. What would be a fast way to append items to this JSON field in database? Maybe there is a library for fast work-around?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Actually what you're doing here is adding another element to a list. And both those elements are dictionaries. This is why you can use the 'append'.
-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

Comments

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.