在Serializer DRF

时间:2018-02-20 11:20:51

标签: python django django-rest-framework

我正在尝试将栅格模型字段与非模型config_version字段组合到我的序列化器中,如下所示:

class RasterPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Raster
        fields = (
            'name',
            'description',
            'filepath'
        )


class ConfigurationSerializer(serializers.Serializer):
    config_version = serializers.CharField()
    rasters = RasterPostSerializer(many=True)

    def create(self, validated_data):
        data_field = validated_data['rasters']
        for raster in data_field['rasters']:
            return Raster(name=raster['name'], description=raster['description'], filepath=raster['filepath'])

在使用serializer.save()方法之前,我想在view.py中检查config_version,但之后.save()给了我:

The serializer field might be named incorrectly and not match any attribute or key on the `Raster` instance.
Original exception text was: 'Raster' object has no attribute 'config_version'.

发生了什么,是否有解决方案?

编辑: 我的示例JSON POST有效负载如下所示:

{
  "config_version":"v2",
  "rasters":[
    {
      "name":"XYZ.jpg",
      "description":"some description",
      "filepath":"path in filesystem"
    }
}

config_version不是常量。它可以动态设置,因为使用ConfigurationSerializer的控制器将是配置端点 - 将来可能需要添加栅格和其他一些信息。

views.py中的

配置端点看起来像

@api_view(['POST'])
def configuration(request):

if request.method == 'POST':
    serializer = ConfigurationSerializer(data=request.data)

    if serializer.is_valid():
        if serializer.validated_data['config_version'] is 'v2':

            raster_name_list = [raster.name for raster in Raster.objects.all()]
            for instance in serializer.validated_data['rasters']:
                if instance['name'] in raster_name_list:
                    return Response({"Fail": "Raster name '{}' already exists".format(instance['name'])}, status=status.HTTP_304_NOT_MODIFIED)
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

2 个答案:

答案 0 :(得分:1)

作为create action的结果,您应该返回ConfigurationSerializer数据。而且我也不知道你将如何处理class ConfigurationSerializer(serializers.Serializer): config_version = serializers.CharField() rasters = RasterPostSerializer(many=True) def create(self, validated_data): config_version = validated_data.get('rasters') rasters = validated_data.pop('rasters') raster_list = [] for raster in rasters: raster_list.append(Raster.objects.create(**raster)) return { "config_version": config_version, "rasters": raster_list }

date.timezone="time"

答案 1 :(得分:0)

您需要一个SerializerMethodField:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

config_version = SerializerMethodField()

def get_config_version(self, obj):
    return YOUR_CUSTOM_DATA