Y
Y
Yeldos Adetbekov2017-03-06 19:08:04
Django
Yeldos Adetbekov, 2017-03-06 19:08:04

How to parse nested object in view in json?

Welcome all! Faced such a problem: I have a model that is linked by a foreign key to another reference. And now I need to submit nested (nested) json data to the view in the context. When the table is not connected to anything, it is easy to do this through the native django.serializer package, but in this case the task is more complicated, and perhaps you cannot do without rest-framework. I must say right away that I have not delved into it yet (All sorts of APIs, etc.) So here is the code:
models.py:

class Directory(models.Model):
  book = models.ForeignKey(Book)
  name = models.CharField(max_length=255,blank=False,null=True)
  description = models.CharField(max_length=1000,blank=True,null=True)
  created_date = models.DateTimeField(default=datetime.now)
  hidden = models.BooleanField(default=False)

  class Meta:
    verbose_name_plural = "Directories"

  def __str__(self):
    return "Dir<" + self.book.name + " - " + self.name + ">"

class FileIn(models.Model):
  directory = models.ForeignKey(Directory, related_name="files")
  name = models.CharField(max_length=255,blank=False,null=True)
  typeof = models.CharField(max_length = 2,choices=FILES_CHOICE,default='F')
  image = models.ImageField(null=True,blank=True,upload_to=upload_location,)
  contents = models.CharField(max_length=1000,blank=True,null=True)
  file = models.FileField(null=True,blank=True,upload_to=upload_location,)
  created_date = models.DateTimeField(default=datetime.now)
  hidden = models.BooleanField(default=False)

serializers.py:
from rest_framework import serializers
from .models import FileIn, Directory
class FileInSerializer(serializers.ModelSerializer):
    class Meta:
        model = FileIn
        fields = ('name', 'typeof', 'image', 'contents', 'file', 'created_date', 'hidden')

class DirectorySerializer(serializers.ModelSerializer):
    files = FileInSerializer(many=True, read_only=True)

    class Meta:
        model = Directory
        fields = ('book','name', 'description', 'created_date','hidden','files')

views.py:
from django.shortcuts import render, redirect
from .serializers import DirectorySerializer
import json
...
def book(request,book_id):
  context={}
  ...
  context["dirs"]=json.dumps(DirectorySerializer().data)
        ...
  return render(request,"book.html",context)

Please help me!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yeldos Adetbekov, 2017-03-06
@dosya97

...
context["dirs"]=json.dumps(DirectorySerializer(Directory.objects.filter(book=Book.objects.get(id=book_id)).order_by("created_date"),many=True, read_only = True).data)
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question