Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ModelSerializer and Mixin

2025-02-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use ModelSerializer and Mixin, the article is very detailed, has a certain reference value, interested friends must read it!

Use serializers.ModelSerializer

After learning about the use of the Serializer class in the serializers module, let's learn how to replace the previous serializers.Serializer class with the serializers.ModelSerializer class in Django

In the last chapter, we wrote the code in serializer.py in Schools APP. Let's take a look at the previous code.

From rest_framework import serializersfrom .models import Schoolclass SchoolSerializer (serializers.Serializer): name = serializers.CharField () desc = serializers.CharField () location = serializers.CharField () create_time = serializers.DateTimeField (default=datetime.now,) course_numbers = serializers.IntegerField () def create (self, validated_data): "" Create and return a new `Snippet` instance, given the validated data. "" Return School.objects.create (* * validated_data)

We defined a SchoolSerializer class, inherited the serializers.Serializer class, and defined five fields in it, right? let's take a look at how to replace the serializers.Serializer class with the serializers.ModelSerializer class.

Class SchoolSerializer (serializers.ModelSerializer): class Meta: # specify Model model to be serialized = School # specify fields in Model to be serialized fields = ('name',' desc') # serialize all fields fields ='_ all__' def create (self, validated_data): "Create and return a new `Snippet` instance Given the validated data. " Return School.objects.create (* * validated_data)

As you can see from the above code, you can use fields to specify fields in the Model that need to be serialized, and you can specify one or two.. Or all fields, if we want to specify serialization of all fields, we can use fields ='_ _ all__'

Let's first take a look at what fields = ('name',' desc') looks like if two fields are serialized:

Try serializing all the fields again: fields ='_ _ all__'

From the code, we can come to the conclusion that using the serializers.ModelSerializer class instead of the serializers.Serializer class, that is, making the SchoolSerializer class in schools app inherit the serializers.ModelSerializer class, can make the code more concise and convenient.

Use mixins.ListModelMixin

Mixins can realize class function or function enhancement, and can dynamically add some properties and methods of function. There are many enhanced mixin in DRF library.

ListModelMixin: list view extension class that provides list (request, args, * kwargs) methods to quickly implement list view and return 200status codes. The list method of the Mixin filters and pages the data.

GenericAPIView: inherits from APIVIew and adds general support methods that may be used for list views and details views. Queryset is the query set for list views, and serializer_class is the serializer used for views.

So now let's edit the views.py file in APP and rewrite the AllSchoolsView class

Class AllSchoolsView (mixins.ListModelMixin,generics.GenericAPIView): "" this is the result returned by AllSchoolsView "" # queryset, serializer_class is fixed queryset = School.objects.all () serializer_class = SchoolSerializer def get (self, request, * args, * * kwargs): return self.list (request, * args, * * kwargs)

The effect of the access interface is the same as before, but the code is less than before. Let's take a look.

Simplify AllSchoolsView with generics.ListAPIView

By looking at the inheritance relationship of ListAPIView, we can see that ListAPIView inherits mixins.ListModelMixin and GenericAPIView:

Class ListAPIView (mixins.ListModelMixin, GenericAPIView):

By modifying the inheritance relationship of AllSchoolsView, we find that if we let AllSchoolsView inherit generics.ListAPIView, the effect of the access interface is the same as before, and we can even omit the get method.

Because the ListAPIView class comes with a get method, this makes the code more concise. Do not put the effect picture, just like the one above

Class AllSchoolsView (generics.ListAPIView): "" this is the result returned by AllSchoolsView "" # queryset, serializer_class is fixed queryset = School.objects.all () serializer_class = SchoolSerializer # def get (self, request, * args, * * kwargs): # return self.list (request, * args, * * kwargs)

There are many encapsulated View in the generics.py under the rest_ framework library

The rule here is that Create means to add, Retrieve means to operate a piece of data, List means to operate multiple pieces of data, Destroy means to delete, and Update means to update.

ListCreateAPIView: used to add multiple pieces of data after post submission

RetrieveAPIView: used to return a piece of data

ListAPIView: used to return data from a table, or multiple pieces of data

CreateAPIView: add a piece of data

The above is all the content of the article "how to use ModelSerializer and Mixin". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report