Road to JSON data with Object and QuerySet data Django

Well, after having some time works on the serialization of my QuerySet data to JSON Response, I’ve understanding how create easily my custom JSON Response. I’ll to explain how do it easily in your own project !

To begin, you need to create a function in your main class. For example :

class Game(models.Model):
nom = models.CharField(max_length=100)
nbGenerate = models.SlugField(max_length=100, null=True)
author = models.CharField(max_length=42, null=True)
description = models.TextField(null=True)
dateAdd = models.DateTimeField(default=timezone.now,
verbose_name="Date de parution")
class Meta:
ordering = ['dateAdd']
def __str__(self):
return self.nom

# This is my custom JSON Response
def serializeCustom(self):
data = {
"name": self.nom,
"author": self.author,
"description": self.description,
"pictures": list(Picture.objects.filter(game__pk=self.id).values('url')),
"urls": list(Url.objects.filter(game__pk=self.id).values('adress')),
}
return data

You can show in this function some attributes, some Game attributes and others like Picture and Url. I’ll to detail the next line :

list(Picture.objects.filter(game__pk=self.id).values('url'))

In this line, the Picture.objects.filter(game__pk=self.id).values(‘url’) give me a QuerySet Object. For return a correct JSON data we need to transform him in dict. So, we just apply a list() on him.

Well, now let’s see the views.py file.

def getRandomGame(request):
game = Game.objects.order_by('?').first()
return JsonResponse(game.serializeCustom())

We can see on the second line a game object is created. (the .first() give a Game Class object in contrary .order_by(‘?’) return a QuerySet Object). To finish we just need to call the serializeCustom Function and it’s done.

The result :

I hope that helps !