Django REST Framework:嵌套的序列化程序无法正确验证数据

时间:2018-01-28 23:52:03

标签: python json django serialization django-rest-framework

我是DRF(和Django)的新手,并尝试创建一个能够验证以下请求数据的嵌套序列化程序:

{
    "code": "12345",
    "city": {
        "name": "atlanta",
        "state": "Georgia"
    },
    "subregion": {
        "name": "otp north"
    }
}

为简化客户端的工作,我希望这个单一的请求在数据库中创建多条记录:

  • 城市(如果匹配的城市尚不存在)
  • 分区域(如果尚未存在匹配分区)
  • 引用城市和(可选)子区域的CodeLog

型号:

class City(models.Model):
    name = models.CharField(max_length=75, unique=True)
    state = models.CharField(max_length=50, blank=True)

class Subregion(models.Model):
    city = models.ForeignKey(City)
    name = models.CharField(max_length=75)

class CodeLog(models.Model):
    code = models.CharField(max_length=10)
    city = models.ForeignKey(City)
    subregion = models.ForeignKey(Subregion, blank=True, null=True)

串行器:

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ('name', 'state')

class SubregionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subregion
        fields = ('name',)

class CodeLogSerializer(serializers.ModelSerializer):
    city = CitySerializer()
    subregion = SubregionSerializer(required=False)

    class Meta:
        model = CodeLog
        fields = ('code', 'city', 'subregion')

    # This is where I'm having troubles
    def create(self, validated_data):
        city_data = validated_data.pop('city', None)
        subregion_data = validated_data.pop('subregion', None)
        if city_data:
            city = City.objects.get_or_create(**city_data)[0]
        subregion = None
        if subregion_data:
            subregion = Subregion.objects.get_or_create(**subregion_data)[0]

        code_log = CodeLog(
            code=validated_data.get('code'),
            city=city,
            subregion=subregion
        )
        code_log.save()
        return code_log

查看:

class CodeLogList(APIView):
    serializer_class = CodeLogSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我能够使用平面请求结构,嵌套序列化器很难掌握。 我是在正确的轨道上,还是有更理想的结构可以更好地运作?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您的Subregion模型的city字段是外键,不能为空。您的create方法应该是这样的。

def create(self, validated_data):
    city_data = validated_data.pop('city', None)
    subregion_data = validated_data.pop('subregion', None)
    if city_data:
        city = City.objects.get_or_create(**city_data)[0]
    subregion = None
    if subregion_data:
        # Add city in Subregion data
        subregion_data.update({'city': city})
        subregion = Subregion.objects.get_or_create(**subregion_data)[0]

    code_log = CodeLog(
        code=validated_data.get('code'),
        city=city,
        subregion=subregion
    )
    code_log.save()
    return code_log