Nested Json for Django multiple foreign key models


Mehmet Ince

I have 4 models with relationships via FK.

class Journal(models.Model):
    name = models.CharField(max_length=255)

class Volume(models.Model):
    journal = models.ForeignKey(Journal, related_name='volumes')
    number = models.IntegerField()

class Issue(models.Model):
    volume = models.ForeignKey(Volume, related_name='issues')
    number = models.IntegerField()

class Article(models.Model):
    issue = models.ForeignKey(Issue, related_name='articles')
    title = models.CharField(max_length=255)

I need JSON format like Follow structure.

journal: [
    { name: 'Volume number goes here', type: 'folder',  id: 'F1',
        data: [
            { name: 'Issue number goes here', type: 'folder', id: 'F1F1',
                data: [
                    { name: 'Article name goes here>', type: 'item', id: 'F1F1I1' },
                    { name: 'Article name goes here>', type: 'item', id: 'F1F1I2' },
                    { name: 'Article name goes here>', type: 'item', id: 'F1F1I3' },
                ]},
            { name: 'Issue number goes here', type: 'folder', id: 'F1F2',
                data: [
                    { name: 'Article name goes here>', type: 'item', id: 'F1F2I1' },
                    { name: 'Article name goes here>', type: 'item', id: 'F1F2I2' },
                    { name: 'Article name goes here>', type: 'item', id: 'F1F2I3' },
                ]},
        ]
    },
    { name: 'Volume number goes here', type: 'folder',  id: 'F2',
        data: [
            { name: 'Issue number goes here', type: 'folder', id: 'F1F1',
                data: [
                    { name: 'Article name goes here>', type: 'item', id: 'F2F1I1' },
                    { name: 'Article name goes here>', type: 'item', id: 'F2F1I2' },
                    { name: 'Article name goes here>', type: 'item', id: 'F2F1I3' },
                ]},
            { name: 'Issue number goes here', type: 'folder', id: 'F1F2',
                data: [
                    { name: 'Article name goes here>', type: 'item', id: 'F2F2I1' },
                    { name: 'Article name goes here>', type: 'item', id: 'F2F2I2' },
                    { name: 'Article name goes here>', type: 'item', id: 'F2F2I3' },
                ]},
        ]
    }
],

I have tried several ways but it will result in hundreds of sql queries (due to the for loop)

Any ideas?

leukocyte

You can use 4 queries to create that JSON file. You just need to use prefetch_related.

Here's some proofs of concept (required for counters to work DEBUG=True):

from django.db import connection

journals = Journal.objects.all().prefetch_related('volumes', 'volumes__issues', 'volumes__issues__articles')

for journal in journals:
    print "%s" % journal.name
    for volume in journal.volumes.all():
        print "  %d" % volume.number
        for issue in volume.issues.all():
            print "    %d" % issue.number
            for article in issue.articles.all():
                print "      %s" % article.title

print len(connection.queries)

This will show a simple tree of your objects and the number of queries at the end, equal to 4 (if no queries were previously performed in that connection). At this point, creating the JSON output is not far off.

Django REST Framework might be helpful when it comes to creating the exact JSON . Using the queryset above for input, assuming you have all serializers done and nested JournalSerializer, will create 4 queries for the database.

Related


Nested Json for Django multiple foreign key models

Mehmet Ince I have 4 models with relationships via FK. class Journal(models.Model): name = models.CharField(max_length=255) class Volume(models.Model): journal = models.ForeignKey(Journal, related_name='volumes') number = models.IntegerField() cl

Django multiple foreign key models

Andre Consart Here is my code, is there a more efficient way to write it? I do not like it. Basically, both the company model and the supplier model should be able to connect with multiple phone numbers. class Contact(models.Model): company = models.Foreig

Django multiple foreign key models

Andre Consart Here is my code, is there a more efficient way to write it? I do not like it. Basically, both the company model and the supplier model should be able to connect with multiple phone numbers. class Contact(models.Model): company = models.Foreig

Django foreign key relationship with multiple models

Pranavar Mohan I have different models with many different types of fields. I want to use foreign keys for multiple models. like: class Model1(models.Model): title = models.TextField() body = models.TextField() class Model2(models.Model): tag

Multiple nested foreign key relationships in Django

No I'm trying to get an object that traverses 2 models that have a reverse foreign key relationship. I've been able to get the object of the first model (ipv4address), but not able to get the object linked to it with a reverse foreign key. I'm new to django, s

Django - Trouble with foreign key models

and TL;DR Access object foreign key, the invoice must have a customer , how can I display the invoice and its customer data in the HTML template? I'm making an invoicing system so I have these models. class Customer(models.Model): name = models.CharField(m

Django foreign keys for multiple models

Tony Dean Is there a way to have one model be able to foreign keys to multiple models? E.g class Tshirt(models.Model): ..... class Jeans(models.Model): ..... class Clothes(models.Model): item = ForeignKey(Tshirt and Jeans, on_delete = models.CASCADE)

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

Double foreign key relationship between models Django

Nick Cuevas I'm a little confused here: class MyBirthday(Model): date = models.DateTimeField() invitations_quantity = models.IntegerField() message = models.CharField(max_length=500) user = models.ForeignKey(User) location = models.OneToOne

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

django ORM join two models on foreign key

David Rice The title may be misleading and I don't know how to express my question I have two models declared this way: class Record(models.Model): # autogen id as primary key name = models.ForeignKey(Product, on_delete=models.DO_NOTHING) value = m

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

Django: Link two models with a common foreign key

tenase I'm new to django and am currently making an admin panel where I can view user orders. I am processing orders according to the following OrderItem model class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Django insert performance with multiple nested models

Thanh Nguyen I have the following model definition: class Workflow(models.Model): name = models.CharField(max_length=255) class Step(models.Model): workflow = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='steps') title = model

Django - Handling multiple nested models at different levels

CH Andre Meloa I have some questions about Django nested models. As far as I know, to handle nested data structures, I have to deserialize each data and then create objects that will be concatenated with the ForeignKeyField. I can handle this by overriding the

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Django insert performance with multiple nested models

Thanh Nguyen I have the following model definition: class Workflow(models.Model): name = models.CharField(max_length=255) class Step(models.Model): workflow = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='steps') title = model