Django-将两个模型序列化器组合为一个JSON响应

时间:2018-10-22 15:50:17

标签: python django django-rest-framework

我有两个型号List和Card。我正在尝试将两者结合起来并做出一个JSON响应

我的列表JSON响应

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

我的卡JSON响应

[
    {
        "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
    },
]

我的serializers.py文件

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__'

我的api.py文件

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

我的模型。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)

如何在“我的列表” JSON响应中实现以下内容?

[
    {
        "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"
    },
]

我尝试这样做,但是无法实现。所以我在这里张贴了

标题

非常感谢。

2 个答案:

答案 0 :(得分:2)

将列表related_name更改为cardsListViewSet会做您想要的事

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 = "cards"
    ,on_delete=models.PROTECT)
...

答案 1 :(得分:0)

您还可以使用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