1
\$\begingroup\$

I built an backend using Django and the django-rest-framework and realized that a lot of the code snippets (mainly classes) are similar. Is there any better way? I tried to wrap them into a very generic class, but didn't succeed yet. This is what I mean by "similar serializers":

...
class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Device


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = User
...

Then there are the viewsets:

...
class DeviceAPI(mixins.ListModelMixin, viewsets.GenericViewSet):
    model = Device
    serializer_class = DeviceSerializer
    queryset = Device.objects.all()


class UserAPI(mixins.ListModelMixin, viewsets.GenericViewSet):
    model = User
    serializer_class = UserSerializer
    queryset = User.objects.all()
...

This goes on for about 150 lines of code as I have a lot of models. I tried wrapping them into one generic serializer and one viewset, but the Swagger generator didn't register all the serializer classes then.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.