In a Python django app, how to store a list of dictionaries in a postgresql database?
- User
In a Python django app, how to store a list of dictionaries in a postgresql database?
Assistant
Here are a few ways to store a list of dictionaries in a PostgreSQL database from a Django app:
JSONField:
Use Django's JSONField to store the list of dicts as a JSON object.
from django.contrib.postgres.fields import JSONField class MyModel(models.Model): dict_list = JSONField()Serialized as text:
Serialize the list to a string using json.dumps() and store in a TextField.
from django.db import models import json class MyModel(models.Model): dict_list = models.TextField() def save(self, *args, **kwargs): if self.dict_list: self.dict_list = json.dumps(self.dict_list) super().save(*args, **kwargs)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.