简体   繁体   English

使用Python将JSON数组附加到另​​一个项目

[英]Append JSON array with another item using Python

I recently migrated to Python and cannot solve quite simple problem (using Django). 我最近迁移到Python,无法解决非常简单的问题(使用Django)。 A model has JSON field (PostgreSQL), lets say, for example, fruits. 模型具有JSON字段(PostgreSQL),例如,水果。 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: 编辑模型时,我想添加另一个水果(追加),因此结果将只有几个JSON项目,并且model.fruits将返回如下值:

[
    {
        "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. 我尝试搜索解决方案,但似乎此字典的append函数会覆盖值,而不是将其追加。 What would be a fast way to append items to this JSON field in database? 将项目追加到数据库中此JSON字段的快速方法是什么? Maybe there is a library for fast work-around? 也许有一个快速解决方法的库?

model.fruits = {"id": 1, "name": "apple"} * defines a dictionary, you cannot append to a dictionary, you can add keys to it model.fruits = {"id": 1, "name": "apple"} *定义字典,您不能追加到字典,可以向其添加键

You can append elements into a JSON array though, eg if model.fruits was an array (or a list, as it is called in Python), eg 但是,您可以将元素追加到JSON数组中,例如,如果model.fruits是数组(或列表,在Python中称为列表),例如

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

which defines an array with 1 element in it, then you can append to it 它定义了一个包含1个元素的数组,然后可以将其追加

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 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 *老实说,以复数形式命名的东西(例如fruits来容纳单个对象没有任何意义,应该是一个容器(如列表)

In Django, you should make a new model called Fruit. 在Django中,您应该创建一个名为Fruit的新模型。

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

in your main model you should have a ManyToManyField . 在您的主模型中,您应该具有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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM