when i create a Serializer in django-rest0-framework, based on a ModelSerializer, i will have to pass the model in the Meta class:
class ClientSerializer(ModelSerializer):
class Meta:
model = Client
I want to create a general serializer which, based on the URL, includes the model dynamically.
My setup thusfar includes the urls.py and the viewset:
urls.py:
url(r'^api/v1/general/(?P<model>w+)', kernel_api_views.GeneralViewSet.as_view({'get':'list'}))
and views.py:
class GeneralViewSet(viewsets.ModelViewSet):
def get_queryset(self):
# Dynamically get the model class from myapp.models
queryset = getattr(myapp.models, model).objects.all()
return queryset
def get_serializer_class(self):
return getattr(myapp.serializers, self.kwargs['model']+'Serializer')
Which in care of: http://127.0.0.1:8000/api/v1/general/Client gets Client.objects.all() as queryset and the ClientSerializer class as serializer
Question: How can i make it so that i can call 'GeneralSerializer' and dynamically assign the model in it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…