Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 535
TidharPeer Avatar asked Aug 21 '13 08:08

TidharPeer


1 Answers

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.

like image 159
Pete Tinkler Avatar answered Oct 08 '22 14:10

Pete Tinkler