在Django Rest框架中更新JSONField [英] Updating JSONField in django rest framework
问题描述
我目前对在django rest-framework中使用JSONField很熟悉,但是我找不到更新存储json中密钥的任何直接方法。过滤JSONField的方法有很多,具体取决于其内部键,但是似乎无法从已存储的JSONField中更改,更新或删除键。但是似乎postgres可以对json键进行一些修改,如此答案所解释的。
I currently became familiar with using JSONField in django rest-framework, but I could not find any straight forward way to update a key in a stored json. There are many ways to filter JSONField depends on its internal keys, but it seems that there is no way to change, update or delete a key from already stored JSONField. But it seems that postgres can do some modifications on json keys as this answer explained.
是否有任何功能可以对JSONFields进行修改。如果没有任何直接命令可以执行此操作,那么实现JSONField修改的最佳方法是什么?
Is there any function which is able to do modifications on JSONFields. If there is not any direct command to do this, what is the best way to implement modifications of a JSONField?
编辑:
例如,如果我有这样的模型:
As an example if I have a model like this:
class Thing(models.Model):
name = models.CharField()
properties = JSONField()
然后在 properties
中存储了一个像这样的json:
And in properties
I stored a json like this :
{
"color" : "red",
"size" : "large",
"cost" : 1234
}
然后我想使用django命令将颜色更改为绿色。
Then I want to change the color to "green" by using django commands.
推荐答案
thing = Thing.objects.get(name="...")
thing.properties['color'] = 'green'
thing.save()
这篇关于在Django Rest框架中更新JSONField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!