beginner_
beginner_

Reputation: 7622

django rest framework: Dynamic serializer and ViewSet

I'm new to django and django rest framework as a disclaimer.

I have a Model that contains metadata columns like last modified date and last modified user. This data should be available in the API for viewing but will be set automatically by the backend and hence must not be required for creation/update. As far as I understood I can create a dynamic serializer as shown in the docs.

However how can I use a dynamic serialize on a ViewSet? Or is that simply not possible?

Upvotes: 0

Views: 418

Answers (1)

Darius Bogdan
Darius Bogdan

Reputation: 957

If you want the last modified date and last modified user to be read only, you do not need to create a DynamicSerializer. All you need to do is to set the fields as read_only on the serializer.

class MyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = (fields exposed to the API)
        read_only_fields = ("last_modified_date", "last_modified_user")

After creating the serializer, it must be added to the ViewSet

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Upvotes: 1

Related Questions