Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - Create a generic serializer with a dynamic model in Meta

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do that by following:

serializers.py

class GeneralSerializer(serializers.ModelSerializer):

    class Meta:
        model = None

views.py

class GeneralViewSet(viewsets.ModelViewSet):

     def get_queryset(self):
         model = self.kwargs.get('model')
         return model.objects.all()           

     def get_serializer_class(self):
         GeneralSerializer.Meta.model = self.kwargs.get('model')
         return GeneralSerializer  

In serializers.py, we define a GeneralSerializer having model in Meta as None. We'll override the model value at the time of calling get_serializer_class().

Then in our views.py file, we define a GeneralViewSet with get_queryset() and get_serializer_class() overridden.

In get_queryset(), we obtain the value of the model from kwargs and return that queryset.

In get_serializer_class(), we set the value of model for GeneralSerializer to the value obtained from kwargs and then return the GeneralSerializer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...