嵌套序列化器中的Django Rest Framework关系查询

i5desfxk  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(159)

我在Django REST框架中实现嵌套序列化器时遇到了困难。
我正在构建一个在线记分板,目前我有三个模型,我正试图将其序列化为一个响应。

模型.py

class Player(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return self.first_name

class Event(models.Model):

    user = models.ManyToManyField("Player")
    name = models.CharField(max_length=50)  
    desc = models.CharField(max_length=225)

    def __str__(self):
        return self.name

class LeadBoard(models.Model):
    """model for LeadBoard"""

    player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='leadboard_player', null=True, blank=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='leadboard_event', null=True, blank=True)
    score = models.IntegerField()

    def __str__(self):
        return self.score

事件模型代表某种体育事件,每个事件可以有多个玩家(* 事件模型中的用户字段 *),排行榜模型存储每个事件中玩家的分数。

序列化程序.py

class PlayerSerializer(serializers.ModelSerializer): 

    class Meta:
        model = Player
        fields = ('id','first_name', 'last_name', 'bio')

class EventSerializer(serializers.ModelSerializer):
    
    user = PlayerSerializer(read_only=True, many=True)
    class Meta:
        model = Event
        fields = ('id', 'name', 'user', 'desc')

class LeadBoardSerializer(serializers.ModelSerializer):

    event = EventSerializer(read_only=True)
    
    class Meta:
        model = LeadBoard
        fields = ('id', 'event', 'score')

我添加了两名玩家

[
            {
                "id": 1,
                "first_name": "Jhon",
                "last_name": "Doe"
            },
            {
                "id": 3,
                "first_name": "Anna",
                "last_name": "Doe"
            }
        ]

及其在排行榜模型中的分数

[
    {
        "id": 1,
        "player": 1,
        "event": 1,
        "score": 20
    },
    {
        "id": 2,
        "player": 3,
        "event": 1,
        "score": 90
    }
]

这是排行榜的回应,

[
    {
        "id": 1,
        "event": {
            "id": 1,
            "name": "event2020",
            "user": [
                {
                    "id": 1,
                    "first_name": "Jhon",
                    "last_name": "Doe"
                },
                {
                    "id": 3,
                    "first_name": "Anna",
                    "last_name": "Doe"
                }
            ],
            "desc": "event description"
        },
        "score": 20
    },
    {
        "id": 2,
        "event": {
            "id": 1,
            "name": "event2020",
            "user": [
                {
                    "id": 1,
                    "first_name": "Jhon",
                    "last_name": "Doe"
                },
                {
                    "id": 3,
                    "first_name": "Anna",
                    "last_name": "Doe"
                }
            ],
            "desc": "event description"
        },
        "score": 90
    }
]

但我期望得到的是这样的响应,它正确地返回事件的玩家(用户)和他们的分数。

[
    {
        "id": 1,
        "event": {
            "id": 1,
            "name": "event2020",
            "user": [
                {
                    "id": 1,
                    "first_name": "Jhon",
                    "last_name": "Doe",
                    "score": 20
                },
                {
                    "id": 3,
                    "first_name": "Anna",
                    "last_name": "Doe",
                    "score": 90
                }
            ],
            "desc": "event description"
        }
    }
]

我错过了什么?
我是Django和Django休息框架的新手。

6jygbczu

6jygbczu1#

你需要通过事件而不是排行榜做出React。

class PlayerSerializer(serializers.ModelSerializer): 

   class Meta:
        model = Player
        fields = ('id','first_name', 'last_name', 'bio')

class LeadBoardSerializer(serializers.ModelSerializer):

    player = PlayerSerializer(read_only=True)

    class Meta:
        model = LeadBoard
        fields = ('id', 'player', 'score')

class EventSerializer(serializers.ModelSerializer):

    leadboard_event = LeadBoardSerializer(read_only=True, many=True)

    class Meta:
        model = Event
        fields = ('id', 'name', 'desc', 'leadboard_event')

现在使用视图获取事件列表

更新1如果您想在玩家中获得分数

class PlayerSerializer(serializers.Serializer):  
    player_id = serializers.IntegerField()
    first_name = serializers.CharField(max_length=256)
    last_name = serializers.CharField(max_length=256)
    score = serializers.IntegerField()

class LeadBoardSerializer(serializers.ModelSerializer):

    player = serializers.SerializerMethodField()

    class Meta:
        model = LeadBoard
        fields = ('id', 'player')

    def get_player(self,obj):
        player_dict = {'player_id': obj.player.id, 'first_name': obj.player.first_name, 'last_name': obj.player.last_name, 'score': obj.score}
        result = PlayerSerializer(data=player_dict)
        return result

class EventSerializer(serializers.ModelSerializer):

    leadboard_event = LeadBoardSerializer(read_only=True, many=True)

    class Meta:
        model = Event
        fields = ('id', 'name', 'desc', 'leadboard_event')

试试看。

相关问题