Django jsonfield save to database

I have a Django model that uses a JsonField field.

At some point, I update the field with the IP address and save this 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. is not it?

But the field was not saved using the ip dictionary element ... and I have no idea why!

I made a workaround that works, but doesn't look good in my code:

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

Thus, JsonField is really stored in the database with an IP address.

Does anyone know why the first approach did not work? and what should I do to fix this?

Thanks!

+4
source share
1 answer

Your example worked fine for me when I tried. Could you tell us what you mean by the field, were not saved? To clarify what I'm testing in the console. Created an application 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 these steps with the same effect? If so, then the error is located elsewhere in your code.

+1
source

Source: https://habr.com/ru/post/1498146/


All Articles