如何在DRF中仅添加GET而不添加POST的序列化器字段?

时间:2019-06-25 16:56:12

标签: django django-rest-framework

我正在使用现有的DRF代码库,并且想添加一个last_build字段以仅在GET请求中返回。我不希望这影响与POST请求有关的任何事情。我创建了一种方法,该方法可以返回要查找的字段,并且已经成功测试了它返回所需的数据,但是我尚未测试这是否会影响现有的POST请求。

class JobSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=True, max_length=150)
    product = ProductSerializer(many=False, required=True)
    platform = PlatformSerializer(many=False, required=True)
    stages = StageSerializer(many=True, required=False)
    last_build = serializers.SerializerMethodField()

    def get_last_build(self, name):
        latest_build = JobExecution.manager.filter(job__name=name.name)
        return latest_build.last().build_id

    class Meta:
        model = Job
        fields = ("name", "product", "platform", "stages", "last_build")
        validators = [
            UniqueTogetherValidator(
                queryset=Job.manager.all(), fields=("name", "platform", "product")
            )
        ]

    def create(self, validated_data):
        # Create objects from data
        try:
            product_data = validated_data.pop("product", None)
            if product_data:
                ps = ProductSerializer()
                validated_data["product"] = ps.create(product_data)
            else:
                logger.exception("product is not valid")

            platform_data = validated_data.pop("platform", None)
            if platform_data:
                ps = PlatformSerializer()
                validated_data["platform"] = ps.create(platform_data)
            else:
                logger.exception("platform is not valid")

            stage_data = validated_data.pop("stages", [])
            stages = []

            the_job = Job.manager.get_or_create(**validated_data)[0]
            if stage_data:
                for stage_data in stage_data:
                    ss = StageSerializer()
                    stage_data["job"] = the_job
                    the_stage = ss.create(stage_data)
            return the_job
        except Exception as e:
            logger.exception(e)
            raise e

这是用于发布的api视图的摘录:

class JobView(GenericAPIView):
    def post(self, request, format=None):
        serializer = JobSerializer(data=request.data)
        logger.debug(request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            logger.info("POST request for Job failed: %s", serializer.errors)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您可以为序列化程序方法添加一些字段以跳过 POST/PUT/PATCH 请求。 添加 required=False 跳过检查数据,read_only=True 跳过 POST 请求。

示例:

class JobSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=True, max_length=150)
    product = ProductSerializer(many=False, required=True)
    platform = PlatformSerializer(many=False, required=True)
    stages = StageSerializer(many=True, required=False)
    last_build = serializers.SerializerMethodField(required=False, read_only=True)