使用ModelSerializer覆盖Django Rest中的验证检查

时间:2017-01-30 07:20:03

标签: python django python-2.7 django-rest-framework

我经历了相关问题并没有找到任何解决方案。

查看

class TestList(viewsets.ModelViewSet):

    serializer_class = TestSerializer
    queryset = Test.objects.all()

模型

class Location(models.Model):
    latitude = models.CharField(max_length=100)
    longitude = models.CharField(max_length=100)

class Test(models.Model):
    video_id = models.CharField(max_length=100)
    location = models.ForeignKey(Location)

串行

class LocationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Location
        fields = ('latitude', 'longitude')


class TestSerializer(serializers.ModelSerializer):

    def validate_location(self, data):
        if type(data['location']) == dict:
            if not (type(data["location"]["latitude"]) == str and len(data["location"]["latitude"]) < 100):
                raise serializers.ValidationError("Latitude field error")
            if not (type(data["location"]["longitude"]) == str and len(data["location"]["longitude"]) < 100):
                raise serializers.ValidationError("Longitude field error")
        else:
            raise serializers.ValidationError("Wrong type")
        return data

    def create(self, validated_data):
        print validated_data
        loc_details = validated_data.pop('location')
        location = Location.objects.create(**loc_details)
        return Test.objects.create(location=location, **validated_data)

    class Meta:
        model = Test
        fields = ('video_id', 'emotions', 'location')

TestSerializer of Test期望location字段为pk。但是我希望在保存测试模型之前接收纬度经度字段并创建一个Location对象。

发布请求格式

{
    "video_id": "sdasd",
    "location": {"latitude":"52.345","longitude":"56.756"}
}

我想获取位置详细信息,创建位置对象,然后将其传递给测试模型。我编写了自定义验证并尝试覆盖&#34;预期的pk值错误&#34;。但它不起作用。如何覆盖验证错误?

1 个答案:

答案 0 :(得分:0)

在您的模型中添加related_name,:

class Location(models.Model):
    latitude = models.CharField(max_length=100)
    longitude = models.CharField(max_length=100)

class Test(models.Model):
    video_id = models.CharField(max_length=100)
    location = models.ForeignKey(Location, related_name='locations')

让你的序列化器像这样:

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test

class LocationSerializer(serializers.ModelSerializer):
    locations = TestSerializer(required=False)
    class Meta:
        model = Location

在您的观看中仅包含LocationSerializer。