In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use serializer in Python Web framework Django". The explanation in this article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use serializer in Python Web framework Django".
Serialization is used to convert data into a format that is convenient for storage or transmission, and then rebuild it for use. DRF is the best known serializer.
Serialization is the process of converting data into a format that can be stored or transmitted, and then rebuilding it. It is always used when developing an application or storing data in a database, memory, or converting it to a file.
I recently helped two junior Labcodes developers understand serializers, and I thought I could share my approach with you.
Suppose you are writing an e-commerce site and you have an order that records that someone bought a product at a certain price on a certain date:
Class Order: def _ _ init__ (self, product, customer, price, date): self.product = product self.customer = customer self.price = price self.date = date
Now, suppose you want to store and retrieve order data from a key-value database. Fortunately, its interface accepts and returns dictionaries, so you need to convert objects into dictionaries:
Def serialize_order (order): return {'product': order.product,' customer': order.customer, 'price': order.price,' date': order.date}
If you want to get some data from the database, you can take the dictionary data and convert it to an order object (Order):
Def deserialize_order (order_data): return Order (product=order_data ['product'], customer=order_data [' customer'], price=order_data ['price'], date=order_data [' date'],)
This is very straightforward for simple data, but it doesn't scale well when you need to deal with complex objects made up of complex attributes. You also need to deal with validation of different types of fields, which requires a lot of manual work.
At this point, the serialization of the framework can come in handy. They allow you to create serializers with a small number of templates, which will apply to complex situations.
Django provides a serialization module that allows you to "convert" the model to other formats:
From django.core import serializers serializers.serialize ('json', Order.objects.all ())
It covers the most commonly used categories of Web applications, such as JSON, YAML, and XML. But you can also use a third-party serializer or create your own serializer. You just need to register it in the settings.py file:
# settings.pySERIALIZATION_MODULES = {'my_format': appname.serializers.MyFormatSerializer,}
To create your own MyFormatSerializer, you need to implement the .serialize () method and accept a query set and other options as parameters:
Class MyFormatSerializer: def serialize (self, queryset, * * options): # serious serialization happening
Now you can serialize the query set into the new format:
From django.core import serializers serializers.serialize ('my_format', Order.objects.all ())
You can use option parameters to define the behavior of the serializer. For example, if you want to define that you want to use nested serialization when dealing with ForeignKeys, or just want the data to return its primary key, you can pass a flat=True parameter as an option and handle it in the method:
Class MyFormatSerializer: def serializer (self, queryset, * * options): if options.get ('flat', False): # don't recursively serialize relationships # recursively serialize relationships
One way to use Django serialization is to use loaddata and dumpdata administrative commands.
DRF serializer
In the Django community, the Django REST framework (DRF) provides the most famous serializer. Although you can use Django's serializer to build a JSON that will respond in API, the serializer in the REST framework provides better functionality to help you process and easily validate complex data.
In the case of an order, you can create a serializer like this:
From restframework import serializers class OrderSerializer (serializers.Serializer): product = serializers.CharField (max_length=255) customer = serializers.CharField (max_lenght=255) price = serializers.DecimalField (max_digits=5, decimal_places=2) date = serializers.DateField ()
Easily serialize its data:
Order = Order ('pen',' renato', 10.50, date.today ()) serializer = OrderSerializer (order) serializer.data# {'product':' pen', 'customer':' renato', 'price':' 10.50, 'date':' 2020-08-16'}
To be able to return an instance from the data, you need to implement two methods: create and update:
From rest_framework import serializers class OrderSerializer (serializers.Serializer): product = serializers.CharField (max_length=255) customer = serializers.CharField (max_length=255) price = serializers.DecimalField (max_digits=5, decimal_places=2) date = serializers.DateField () def create (self, validated_data): # execute order creation return order def update (self, instance, validated_data): # execute instance Update return instance
You can then validate the data by calling is_valid () and create or update the instance by calling save ():
Serializer = OrderSerializer (* * data) # # to validate data, you must execute serializer.is_valid () serializer.save () model serializer before calling save
When serializing data, you usually need to process the data from the database (that is, the model you create). ModelSerializer, like ModelForm, provides an API for creating serializers from models. Suppose you have an order model:
From django.db import models class Order (models.Model): product = models.CharField (max_length=255) customer = models.CharField (max_length=255) price = models.DecimalField (max_digits=5, decimal_places=2) date = models.DateField ()
You can create a serializer for it like this:
From rest_framework import serializers class OrderSerializer (serializers.ModelSerializer): class Meta: model = Order fields ='_ _ all__'
Django automatically includes all model fields in the serializer and creates create and udpate methods.
Using serializers in a class-based view (CBV)
Like Forms in Django CBV, serializers integrate well with DRF. You can set the serializer_class property to make it easier for the serializer to use for the view:
From rest_framework import generics class OrderListCreateAPIView (generics.ListCreateAPIView): queryset = Order.objects.all () serializer_class = OrderSerializer
You can also define the get_serializer_class () method:
From rest_framework import generics class OrderListCreateAPIView (generics.ListCreateAPIView): queryset = Order.objects.all () def get_serializer_class (self): if is_free_order (): return FreeOrderSerializer return OrderSerializer
There are other ways to interact with serializers in CBV. For example, get_serializer () returns a serializer that has been instantiated, and get_serializer_context () returns the parameters passed to the serializer when the instance was created. For views that create or update data, there are create and update, which use the is_valid method to validate the data, and perform_create and perform_update that call the serializer's save method.
Thank you for reading, the above is the content of "how to use serializer in Python Web framework Django". After the study of this article, I believe you have a deeper understanding of how to use serializer in Python Web framework Django. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.