Dynamically Create JSON with Foreign Fields nested in Django

I struggled a lot to create a JSON object which should also contain foreign field values.
So after Googling and trying a lot, I came up with this masterpiece code 🙂
This code is very simple does not require any JSON serialization.

In the code below, we are creating a JSON objects for a Quiz app with Question Model, and Choices Model
the choices model is a foreign field (one to many – one question can have many choices) to Question model.

we first convert the queryset to a list so it’s easier to iterate.
rest you can understand by looking at the code itself.

allQuestions = list(Question.objects.all())

data = []

for questionObj in allQuestions:
 item = {"id":questionObj.id, "question": questionObj.question, "choices":[]}

 for choiceObj in questionObj.choices.all():
  item["choices"].append({"position":choiceObj.position, "choice":choiceObj.choice})

 data.append(item)

Data will contain JSON like shown here

[
 {
  "id": 2,
  "question": "What is the capital of India?",
  "choices": [
   {
    "position": 1,
    "choice": "Mumbai"
   },
   {
    "position": 2,
    "choice": "Delhi"
   },
   {
    "position": 3,
    "choice": "Goa"
   }
  ]
 },
 {
  "id": 3,
  "question": "Why so serious?",
  "choices": [
   {
    "position": 1,
    "choice": "Batman"
   },
   {
    "position": 2,
    "choice": "Joker"
   },
   {
    "position": 3,
    "choice": "Monkey"
   },
   {
    "position": 4,
    "choice": "Bunny"
   }
  ]
 }
]

Leave a Reply

Your email address will not be published.