Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - combining two models serializer into one JSON response

I have two models List and Card. I'm trying to combine these two and make a single JSON response

My List JSON response

[
    {
        "id": 1,
        "name": "List of things to do"
    },
    {
        "id": 2,
        "name": "one more"
    }
] 

My Card JSON response

[
    {
        "id": 1,
        "title": "My first scrum card",
        "description": "list things todo here",
        "story_points": null,
        "business_value": null,
        "list": 1
    },
    {
        "id": 2,
        "title": "File my taxes",
        "description": "fill it before 1st of nov",
        "story_points": null,
        "business_value": null,
        "list": 1
    },
]

My serializers.py file

from rest_framework import serializers
from .models import List, Card

class CardSerializer(serializers.ModelSerializer):

    class Meta:
        model = Card
        fields = '__all__'

class ListSerializer(serializers.ModelSerializer):
    cards = CardSerializer(read_only=True, many=True)

    class Meta:
        model = List
        fields ='__all__'

My api.py file

from rest_framework.viewsets import ModelViewSet
from .models import List, Card
from .serializers import ListSerializer, CardSerializer

class ListViewSet(ModelViewSet):
    queryset = List.objects.all()
    serializer_class = ListSerializer

class CardViewSet(ModelViewSet):
    queryset = Card.objects.all()
    serializer_class = CardSerializer

My models.py

from django.db import models

class  List(models.Model):
    name = models.CharField(max_length=50) 

    def __str__(self):
        return "List : {}".format(self.name)

class Card(models.Model): # to create card table
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True) 
    list = models.ForeignKey(List, related_name = "card" 
    ,on_delete=models.PROTECT) # creating a foriegn key for storing list
    story_points = models.IntegerField(null=True, blank = True)
    business_value = models.IntegerField(null=True, blank = True)
    def __str__(self):
        return "Card : {}".format(self.title)

How can I achieve something like below in My List JSON response ?

[
    {
        "id": 1,
        "cards":[
        {
            "id": 1,
            "title": "My first scrum card",
            "description": "list things todo here",
            "story_points": null,
            "business_value": null,
            "list": 1
        }],
        "name": "List of things to do"
    },
    {
        "id": 2,
        "cards":[
        {
            "id": 2,
            "title": "File my taxes",
            "description": "fill it before 1st of nov",
            "story_points": null,
            "business_value": null,
            "list": 1
        }],
        "name": "one more"
    },
]

I have tried to do it but I was unable to implement it. So I posted it here.

Heading

Many thanks.

like image 564
Sheshan Avatar asked Sep 13 '25 22:09

Sheshan


1 Answers

You can also use SerializerMethodeField https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield.

class ListSerializer(serializers.ModelSerializer):
    cards = serializers.SerializerMethodField()

    class Meta:
       model = List
       fields = '__all__'

   def get_cards(self, obj):
       data = CardSerializer(obj.card.all(), many=True).data
       return data
like image 187
ocobacho Avatar answered Sep 16 '25 11:09

ocobacho