0

I am making a lot of views and serializers for my models that takes all fields. They all look like this:

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


class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

I would like to make a generic Viewset and Serializer for that can simply take inn my model. I found this post to be helpful, but I would rather not have the model in the url. If possible, I would send the model with the router.register:

router.register('my_url', MyView(MyModel), basename='my-basename')

but this gives me an error:

AttributeError: This method is available only on the class, not on instances.

Any idea of how I can solve this?

1 Answers1

0

I came across when looking for the same problem. Note that in your GeneralViewSet you have to get the model from self.model. So the correct code for looping all models:

classes={}
for model in django.apps.apps.get_models():
    name = model.__name__
    classes[name]=type(name, (views.GeneralViewSet,), {})
    classes[name].model=model
    router.register(name ,classes[name], basename=name)  
rokdd
  • 541
  • 4
  • 14