django jsonfield保存到数据库

时间:2021-10-22 22:52:36

I have a Django model that uses a JsonField field.

我有一个使用JsonField字段的Django模型。

In some point, I update the field with an IP address, and save that field:

在某些时候,我使用IP地址更新字段,并保存该字段:

class Agent(models.Model):
    properties = jsonfield.JSONField(default = {})

def save_ip_address(self, ip_address):
    self.properties['ip'] = ip_address
    self.save()

Looks pretty straight forward.. isn't it?

看起来很直接..不是吗?

But the field wasn't saved with the ip dictionary item... and I have no idea why!

但是这个字段没有用ip字典项保存......我不明白为什么!

I did a workaround that works but doesn't look good in my code:

我做了一个有效的解决方法,但在我的代码中效果不佳:

d = self.properties
d['ip'] = ip_address
self.properties = d 
self.save()

This way the JsonField is indeed being saved in the database with the IP address.

这样,JsonField确实被保存在具有IP地址的数据库中。

Does anyone know why the first approach didn't work? and what should I do to fix it?

有谁知道为什么第一种方法不起作用?我该怎么做才能解决这个问题?

Thanks!

1 个解决方案

#1


1  

Your example worked just fine for me when I tried it. Could you elaborate on what you mean by the field wasn't saved? To clarify I am testing in the console. Created an app with your model in it, opened the django console and ran:

当我尝试时,你的例子对我来说效果很好。你能详细说明你的意思是没有保存吗?澄清我在控制台测试。用你的模型创建了一个应用程序,打开django控制台并运行:

>>> from test_app.models import Agent
>>> a = Agent()
>>> a.properties = {"host": "test"}
>>> a.save()
>>> a.properties
{'host': 'test'}
>>> a.save_ip_address("127.0.0.1")
>>> a.properties
{'ip': '127.0.0.1', 'host': 'test'}

Can you recreate those steps to the same effect? If so the bug is elsewhere in your code.

你可以重新创建这些步骤以达到同样的效果吗?如果是这样,bug就会出现在代码的其他地方。

#1


1  

Your example worked just fine for me when I tried it. Could you elaborate on what you mean by the field wasn't saved? To clarify I am testing in the console. Created an app with your model in it, opened the django console and ran:

当我尝试时,你的例子对我来说效果很好。你能详细说明你的意思是没有保存吗?澄清我在控制台测试。用你的模型创建了一个应用程序,打开django控制台并运行:

>>> from test_app.models import Agent
>>> a = Agent()
>>> a.properties = {"host": "test"}
>>> a.save()
>>> a.properties
{'host': 'test'}
>>> a.save_ip_address("127.0.0.1")
>>> a.properties
{'ip': '127.0.0.1', 'host': 'test'}

Can you recreate those steps to the same effect? If so the bug is elsewhere in your code.

你可以重新创建这些步骤以达到同样的效果吗?如果是这样,bug就会出现在代码的其他地方。