gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:30:23 24 4
gpt4 key购买 nike

我有两个模型列表和卡片。我正在尝试将这两者结合起来并生成一个 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

我的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)

如何在“我的列表”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"
},
]

我尝试过这样做,但无法实现。所以我把它贴在这里。

标题

非常感谢。

最佳答案

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

关于python - Django - 将两个模型序列化器合并为一个 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com