我们可以将 query_param 值分配给序列化器中的字段吗

问题描述 投票:0回答:2

我有一个

views.py

class ProductImageAPIView(generics.GenericAPIView):
    serializer_class = ProductImageSerializer
    
    def post(self, request):
        query_params = self.request.query_params
        serializer = self.serializer_class(data = request.data, context = query_params)
        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)

serializers.py

class ProductImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField()
    product = serializers.PrimaryKeyRelatedField(allow_null = False, read_only = True)
    
    class Meta:
        model = Image
        fields = ['id', 'image', 'product']

    def validate(self, attrs):
        productParam = self.context.get('product')
        return super().validate(attrs)

我将

query_params
作为上下文发送到序列化程序中。我想知道,如何为
product
字段分配
productParam
值,以便我可以验证它并在 Meta 类的
fields
部分中使用它。

django django-rest-framework django-serializer
2个回答
0
投票

您可以覆盖序列化程序的

to_internal_value
方法以在序列化程序中获得此行为。像这样:

# serializer
class ProductImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField()
    product = serializers.PrimaryKeyRelatedField(allow_null = False, read_only = True)
    
    class Meta:
        model = Image
        fields = ['id', 'image', 'product']

    def to_internal_value(self, data):
        if 'product' not in data:
            data['product'] = self.context['request'].query_params.get('product')
        return super().to_internal_value(attrs)


# view
class ProductImageAPIView(generics.GenericAPIView):
    serializer_class = ProductImageSerializer
    # No need to override the `post` method

有关更多信息,请参阅有关DRF字段的文档以了解

to_internal_value

的使用

0
投票

能够通过覆盖

create
方法
serializers.py

来解决它
def create(self, validated_data):
    productId = self.context.get('product') # This is the query param obtained
    product = Product.objects.get(id = productId)
    validated_data['product'] = product
    return super().create(validated_data)
© www.soinside.com 2019 - 2024. All rights reserved.