簡體   English   中英

django jsonfield保存到數據庫

[英]django jsonfield save to the database

我有一個使用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'}

你可以重新創建這些步驟以達到同樣的效果嗎? 如果是這樣,bug就會出現在代碼的其他地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM