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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With