Django rest framework: override create() in ModelSerializer passing an extra parameter

前端 未结 2 326
小鲜肉
小鲜肉 2021-01-11 13:31

I am looking for a way to properly ovverride the default .create() method of a ModelSerializer serializer in Django Rest Framework for dealing with

相关标签:
2条回答
  • 2021-01-11 13:49

    Hmm. this might not be the perfect answer given I don't know how you want to pass this "extra" in (ie. is it an extra field in a form normally, etc)

    What you'd probably want to do is just represent foo as a field on the serializer. Then it will be present in validated_data in create, then you can make create do something like the following

    def create(self, validated_data):
        obj = OriginalModel.objects.create(**validated_data)
        obj.save(foo=validated_data['foo'])
        return obj
    

    You'd probably want to look at the default implementation of create for some of the other things it does though (like remove many-to-many relationships, etc.).

    0 讨论(0)
  • 2021-01-11 13:59

    You can now do this in the view set (threw in user as a bonus ;) ):

    class OriginalModelViewSet(viewsets.ModelViewSet):
        """
        API endpoint that allows OriginalModel classes to be viewed or edited.
        """
        serializer_class = OriginalModelSerializer
        queryset =  OriginalModel.objects.all()
        def perform_create(self, serializer):
            user = None
            if self.request and hasattr(self.request, "user"):
                user = self.request.user
            serializer.save(user=user, foo='foo')
    

    That way the Serializer can stay generic, i.e.:

    class OriginalModelSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = OriginalModel
            fields = '__all__'
    
    0 讨论(0)
提交回复
热议问题