简体   繁体   中英

django jsonfield save to the database

I have a Django model that uses a JsonField field.

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

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!

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.

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

Thanks!

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:

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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