python - django jsonfield 保存到数据库

标签 python database django json

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

有时,我用 IP 地址更新该字段,并保存该字段:

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

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

看起来很简单..不是吗?

但该字段并未与 ip 字典项一起保存...我不知道为什么!

我做了一个可行的解决方法,但在我的代码中看起来不太好:

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

这样 JsonField 确实与 IP 地址一起保存在数据库中。

有谁知道为什么第一种方法不起作用?我应该怎么做才能修复它?

谢谢!

最佳答案

当我尝试时,您的示例对我来说效果很好。您能否详细说明未保存该字段的意思?澄清一下,我正在控制台中进行测试。使用您的模型创建一个应用程序,打开 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'}

您能否重新创建这些步骤以达到相同的效果?如果是这样,则错误在您的代码中的其他地方。

关于python - django jsonfield 保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18352209/

相关文章:

python - docker build 期间没有名为 'numpy' 的模块

sql - 外键关系和 "belongs to many"

python - Django celery 导入错误 : no module named celery when using gunicorn bind?

python - 使用开始日期和结束日期列重新采样

python - Sympy - 比较带有等号 (=) 的等价表达式

python - 为什么我的 protected 循环出错?

mysql - 如何在 MySQL 中收缩/清除 ibdata1 文件

sql - Forking(postgreSQL数据库结构

asp.net - 如何为facebook开发应用程序?

Django:返回 values_list 的字典列表?