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

24👍

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.).

👤Alex T

14👍

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__'
👤davmor

Leave a comment