Django PostgreSQL JSONField: Storing Dictionaries
In Django, you can store a dictionary in a PostgreSQL database by using the 'JSONField'. The 'JSONField' is a field in Django that maps to the JSON data type in PostgreSQL.
To store a dictionary in a 'JSONField', you can simply pass the dictionary as a value when creating or updating a model instance. For example:
from django.db import models
from django.contrib.postgres.fields import JSONField
class MyModel(models.Model):
data = JSONField()
To create an instance of the 'MyModel' model with a dictionary as the 'data' field, you can do:
my_model = MyModel.objects.create(data={'key1': 'value1', 'key2': 'value2'})
To update the 'data' field of an existing instance:
my_model.data = {'key3': 'value3', 'key4': 'value4'}
my_model.save()
To query the 'data' field:
MyModel.objects.filter(data__key1='value1')
This will return all instances of 'MyModel' where the 'data' field has a key with the value 'value1'.
原文地址: https://www.cveoy.top/t/topic/mynS 著作权归作者所有。请勿转载和采集!