简体   繁体   中英

DRF using serializers with a dynamic primary key

Our API has a model defined:

class Job(models.Model):
    file = models.FileField('File')
    xml = models.FileField('XML')

There is a basic serializer:

class XmlSerializer(serializers.ModelSerializer)
    file = serializers.FileField(read_only=True)
    xml = serializers.FileField(required=True)

    class Meta:
        model = Job
        fields = '__all__'

We don't want to change the file but we do want to change the xml field. The xml is uploaded by a system that doesn't know the primary key. Of course we need this to update the model.

I have the following code at the moment:

class ProcessXml(mixins.CreateModelMixin, generics.GenericAPIView):
    serializer_class = XmlSerializer

    def post(self, request, format=None):
        pk = 200
        serializer = XmlSerializer(request.data)
        return Response({})

pk = 200 serves as an example instead of the code we use to parse the xml. I know this doesn't work but it's to show my intention (more or less).

I have tried to use

id = serializers.SerializerMethodField()

def get_id(self, obj):
    return 200

without success.

How do I get this primary key into the the serializer?

I was making it much too difficult. The solution was pretty easy.

class ProcessXml(mixins.CreateModelMixin, generics.GenericAPIView):
    serializer_class = XmlSerializer

    def post(self, request, format=None):
        id = magic_xml_parser_function()

        job = get_object_or_404(Job, pk=id)
        serializer = XmlSerializer(job, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

magic_xml_parser_function() contains the id we found in the xml. This solved it for us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM