django: convert queryset with related objects to json

  • Last Update :
  • Techknowledgy :

There is no default way to create the nested dicts you're after, but you can select the values of related items:

# No need
for select_related in this
case
Event.objects.values('name', 'date', 'place__name', 'place__address')

[{
   "name": "event1",
   "date": "date1",
   "place__name": "place1",
   "place__address": "address1",
}, {
   "name": "event2",
   "date": "date2",
   "place__name": "place2",
   "place__address": "address2",
}]

There is a relevant method called model_to_dict:

from django.forms.models
import model_to_dict
model_to_dict(instance, fields = [], exclude = [])

Suggestion : 2

jQuery Tutorial ,Django: convert QuerySet with related objects to JSON

Finally, I used the following code:

from collections
import defaultdict
city_list = defaultdict(list)

for any_city in City.objects.annotate(CountryName = F('Country__CountryName')).values('CityName', 'CountryName'):
   city_list[any_city['CountryName']].append(any_city['CityName'])
return HttpResponse(json.dumps(city_list))

Suggestion : 3

Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or an aggregate expression (averages, sums, etc.) that has been computed over the objects that are related to the objects in the QuerySet.,This method efficiently updates the given fields on the provided model instances, generally with one query, and returns the number of objects updated:,The additional queries in prefetch_related() are executed after the QuerySet has begun to be evaluated and the primary query has been executed.,When using multiple databases with prefetch_related_objects, the prefetch query will use the database associated with the model instance. This can be overridden by using a custom queryset in a related lookup.

for e in Entry.objects.all():
   print(e.headline)
async
   for e in Entry.objects.all():
   results.append(e)
entry_list = list(Entry.objects.all())
if Entry.objects.filter(headline = "Test"):
   print("There is at least one Entry with the headline Test")
>>>
import pickle
   >>>
   query = pickle.loads(s) # Assuming 's'
is the pickled string. >>>
   qs = MyModel.objects.all() >>>
   qs.query = query # Restore the original 'query'.
>>> import pickle
>>> qs = Blog.objects.values_list('id', 'name')
>>> qs
<QuerySet [(1, 'Beatles Blog')]>
>>> reloaded_qs = Blog.objects.all()
>>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
>>> reloaded_qs
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

Suggestion : 4

Post date April 2, 2022 ,© 2022 The Web Dev

For instance, we write

answers_list = list(answers)

Suggestion : 5

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, or other content types. The arguments in the serialize function are the format to serialize the data.,In the 'views.py', we have imported 'serializers', 'HttpResponse', and the 'Employee' model. If you're using Python 2.6 or later, Django will use the built-in JSON module automatically.,In this article, you will learn a simple process to serialize a MySQL queryset to JSON and display it in the template using Django.,If you're using UTF-8 or any other non-ASCII encoding data with the JSON serializer, you must pass ensure_ascii=False as a parameter to the serialize() call. Otherwise, the output won't be encoded correctly.

Let's start the process by creating an empty project 'company' and application 'employee'-

(env) c: \python37\ Scripts\ projects > django - admin startproject company

(env) c: \python37\ Scripts\ projects > cd blog

(env) c: \python37\ Scripts\ projects\ blog > django - admin startapp employee

After creating the application, add it's name in 'settings.py', so that Django can read this-

INSTALLED_APPS = [
   ....
   ....
   'latestnews',
]

It is also required to edit the database settings in 'settings.py'-

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'company',
      'USER': 'root',
      'PASSWORD': '',
      'HOST': 'localhost',
      'PORT': '3306'
   }
}

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, or other content types. The arguments in the serialize function are the format to serialize the data.

from django.shortcuts
import render
from django.core
import serializers
from django.http
import HttpResponse
from.models
import Employee

# Create your views here.

def displayData(request):
   form = Employee()
data = Employee.objects.all()
post_list = serializers.serialize('json',
   list(data),
   fields = ('emp_name', 'email', 'phone'))
return HttpResponse(post_list)

Here, we have added the path to route the page to a given link.

from django.contrib
import admin
from django.urls
import path
from employee
import views

urlpatterns = [
   path('displaydata', views.displayData),
]