Django Rest Framework嵌套的序列化程序对象为null

时间:2019-12-23 18:43:39

标签: python django django-rest-framework

我使用Django Rest Framework建立了两个模型。一个模型是将嵌套的序列化器嵌套到另一个对象中。一种模型是 Player ,另一种模型是 TeamData 。我希望将TeamData嵌套到Player中。

# models.py
from django.db import models


class TeamData(models.Model):
    urlName = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    nickname = models.CharField(max_length=50)
    tricode = models.CharField(max_length=3)

    def __str__(self):
        return self.city


class Player(models.Model):
    firstName = models.CharField(max_length=100)
    lastName = models.CharField(max_length=100)
    jersey = models.CharField(max_length=10)
    pos = models.CharField(max_length=10)
    posExpanded = models.CharField(max_length=10)
    heightFeet = models.CharField(max_length=2)
    heightInches = models.CharField(max_length=2)
    weightPounds = models.CharField(max_length=5)
    personId = models.CharField(max_length=50)
    teamData = models.ForeignKey(
        TeamData, on_delete=models.CASCADE,  null=True, blank=True)
    isAllStar = models.BooleanField()
    orderChar = models.CharField(max_length=1)
    playerUrl = models.CharField(max_length=50)
    displayName = models.CharField(max_length=100)



#serializer.py
from rest_framework import serializers
from .models import *


class TeamDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = TeamData
        fields = ('id', 'urlName', 'city', 'nickname', 'tricode')


class PlayerSerializer(serializers.ModelSerializer):

    teamData = TeamDataSerializer('teamData')

    class Meta:
        model = Player
        fields = ('id', 'firstName', 'lastName', 'jersey', 'pos',
                  'posExpanded', 'heightInches', 'weightPounds', 'personId',
                  'teamData', 'isAllStar', 'orderChar', 'playerUrl', 'displayName')

    def create(self, validated_data):
        teamData = validated_data.pop('teamData')
        player = Player.objects.create(**validated_data)
        return player


#views.py
from rest_framework import viewsets
from .models import Player, TeamData
from rest_framework import viewsets, permissions
from .serializers import *
class PlayerViewSet(viewsets.ModelViewSet):
    queryset = Player.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = PlayerSerializer

当我执行

的POST请求时
{
        "firstName": "Ste",
        "lastName": "Adams",
        "jersey": "12",
        "pos": "C",
        "posExpanded": "Center",
        "heightFeet": "6",
        "heightInches": "11",
        "weightPounds": "265",
        "personId": "203500",
        "teamData": {
            "id": "1",
            "urlName": "thunder",
            "city": "Oklahoma City",
            "nickname": "Thunder",
            "tricode": "OKC"
        },
        "isAllStar": false,
        "orderChar": "A",
        "playerUrl": "/players/steven/adams/203500",
        "displayName": "Adams, Steven"
    }

我回来

{
    "id": 6,
    "firstName": "Ste",
    "lastName": "Adams",
    "jersey": "12",
    "pos": "C",
    "posExpanded": "Center",
    "heightInches": "11",
    "weightPounds": "265",
    "personId": "203500",
    "teamData": null,
    "isAllStar": false,
    "orderChar": "A",
    "playerUrl": "/players/steven/adams/203500",
    "displayName": "Adams, Steven"
}

任何想法,为什么teamData为null?我怀疑这可能与 视图,但我不确定是什么问题。

1 个答案:

答案 0 :(得分:2)

您无缘无故将 字符串 传递给 PlayerSerializer 。应该是

class PlayerSerializer(serializers.ModelSerializer):
    teamData = TeamDataSerializer() # without passing anything to the serializer

    # other code

另外,您不是在序列化程序的 TeamData 方法中创建 create() 实例。


#final code sample
class PlayerSerializer(serializers.ModelSerializer):
    teamData = TeamDataSerializer()

    class Meta:
        model = Player
        fields = ('id', 'firstName', 'lastName', 'jersey', 'pos',
                  'posExpanded', 'heightInches', 'weightPounds', 'personId',
                  'teamData', 'isAllStar', 'orderChar', 'playerUrl', 'displayName')

    def create(self, validated_data):
        validated_data['teamData'] = TeamData.objects.create(**validated_data.get('teamData', {}))
        player = Player.objects.create(**validated_data)
        return player