Serializing objects containing django querysets

2024/9/27 23:23:43

Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?

I want to serialize the following dictionary:

dictionary = { 'alfa': queryset1, 'beta': queryset2, } 

I decided to do this using simplejson (comes with django). I extended simplejson.JSONEncoder the following way:

from django.utils import simplejson
from django.core import serializersclass HandleQuerySets(simplejson.JSONEncoder):""" simplejson.JSONEncoder extension: handle querysets """def default(self, obj):if isinstance(obj, QuerySet):return serializers.serialize("json", obj, ensure_ascii=False)return simplejson.JSONEncoder.default(self, obj)

Then I do: simplejson.dumps( dictionary, cls=HandleQuerySets), but the returned dicionary looks like this:

{ "alfa": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]","beta": "[{\"pk\": 1, \"model\": \"someapp.somemodel\", \"fields\": {\"name\": \"alfa\"}}]" }

Django-generated JSON is inserted to the dictionary as string, not JSON. What am I doing wrong?

Answer

The correct way to do this would be:

from django.utils import simplejson
from django.core import serializers
from django.db.models.query import QuerySetclass HandleQuerySets(simplejson.JSONEncoder):""" simplejson.JSONEncoder extension: handle querysets """def default(self, obj):if isinstance(obj, QuerySet):return serializers.serialize("python", obj, ensure_ascii=False)return simplejson.JSONEncoder.default(self, obj)

Because serializers.serialize("json", [...]) returns a string ; if you ask for the python serializer, you get a dictionnary, and json encodes whatever is returned by your encoder's default method. Look at the json documentation for details.

You will have to handle more types in your encoder class (such as datetime objects), but you get the idea.

https://en.xdnf.cn/q/71410.html

Related Q&A

How do I list my scheduled queries via the Python google client API?

I have set up my service account and I can run queries on bigQuery using client.query(). I could just write all my scheduled queries into this new client.query() format but I already have many schedule…

What does conda env do under the hood?

After searching and not finding, I must ask here:How does conda env work under the hood, meaning, how does anaconda handle environments?To clarify, I would like an answer or a reference to questions l…

Numpy array larger than RAM: write to disk or out-of-core solution?

I have the following workflow, whereby I append data to an empty pandas Series object. (This empty array could also be a NumPy array, or even a basic list.)in_memory_array = pd.Series([])for df in list…

Pandas DataFrame styler - How to style pandas dataframe as excel table?

How to style the pandas dataframe as an excel table (alternate row colour)? Sample style:Sample data: import pandas as pd import seaborn as snsdf = sns.load_dataset("tips")

Remove namespace with xmltodict in Python

xmltodict converts XML to a Python dictionary. It supports namespaces. I can follow the example on the homepage and successfully remove a namespace. However, I cannot remove the namespace from my XM…

Groupby count only when a certain value is present in one of the column in pandas

I have a dataframe similar to the below mentioned database:+------------+-----+--------+| time | id | status |+------------+-----+--------+| 1451606400 | id1 | Yes || 1451606400 | id1 | Yes …

how to save tensorflow model to pickle file

I want to save a Tensorflow model and then later use it for deployment purposes. I dont want to use model.save() to save it because my purpose is to somehow pickle it and use it in a different system w…

PySide2 Qt3D mesh does not show up

Im diving into Qt3D framework and have decided to replicate a simplified version of this c++ exampleUnfortunately, I dont see a torus mesh on application start. Ive created all required entities and e…

Unable to import module lambda_function: No module named psycopg2._psycopg aws lambda function

I have installed the psycopg2 with this command in my package folder : pip install --target ./package psycopg2 # Or pip install -t ./package psycopg2now psycopg2 module is in my package and I have crea…

RestrictedPython: Call other functions within user-specified code?

Using Yuri Nudelmans code with the custom _import definition to specify modules to restrict serves as a good base but when calling functions within said user_code naturally due to having to whitelist e…