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?
To build on Rahul's answer, this is what worked for me:
urls.py
serializers.py
views.py
So far I know you cannot create a generic serializer if you use model serializer, but you can get the same solution using a base class and deriving all your models from that base class. Implement a method to return the serializer and then use that method to generate a dynamic serializer. I am using this technique for the last 2 years and working pretty fine for me -
Now derive your models from it -
if you want to override the serializer then just do it in the one that you need. for example -
Thats it, now each class has its own dynamic serializer but we just defined it in one place.
Now use the serializer in view set -
and go on from there.
You can do that by following:
serializers.py
views.py
In
serializers.py
, we define aGeneralSerializer
havingmodel
inMeta
asNone
. We'll override themodel
value at the time of callingget_serializer_class()
.Then in our
views.py
file, we define aGeneralViewSet
withget_queryset()
andget_serializer_class()
overridden.In
get_queryset()
, we obtain the value of themodel
fromkwargs
and return that queryset.In
get_serializer_class()
, we set the value ofmodel
forGeneralSerializer
to the value obtained fromkwargs
and then return theGeneralSerializer
.Create general serializer without
model
inMeta
:Add
model
to serializer in ``: