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
-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
- Django – filter form field queryset based on another field
- How to use django-newsletter app's views and forms
- HTTP headers in Django
- Form.is_valid is not validating