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 the Django serialization component Serializers

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I will talk to you about how to use the Django serialization component Serializers, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

01. Why use serialized components

We know that the front and back end often interact with json data structures, and at the back end we often want to return an object to the front end, but json serialization cannot serialize objects (but you can add serialization parameters encoder serialization principles and serialization components almost need to define their own serialization classes and return structures), so we have our serialization components, and we can customize specific structures to return object serialization to the front end. At the same time, it can check the data of the parameters passed in the front end and other functions.

02. Basic use of serialization components

Models

From django.db import models# Create your models here.class Book (models.Model): id = models.IntegerField (primary_key=True) title = models.CharField (max_length=255) desc = models.CharField (max_length=255) is_deleted = models.IntegerField (choices= [(1, "delete"), (0, "not deleted")]) author = models.CharField (max_length=255)

Serializer

From rest_framework.serializers import Serializerfrom rest_framework import serializersclass BookSerializer (Serializer): id = serializers.IntegerField () title = serializers.CharField () desc = serializers.CharField () is_deleted = serializers.ChoiceField (choices= [(1, "delete"), (0, "not deleted")], source= "get_is_deleted_display") author = serializers.CharField ()

Views

From app01.models import Bookfrom app01.serializer import BookSerializerfrom django.http import HttpResponse, JsonResponse# Create your views here.def get_books (request): books = Book.objects.all () se = BookSerializer (books, many=True) return JsonResponse (se.data, safe=False)

The result returns:

[{"id": 1, "title": "alive", "desc": "telling the Life of a Generation", "is_deleted": "not deleted", "author": "Yu Hua"}]

Model and serializer are very similar in writing, but the inherent logic model is the relational mapping with database tables, and serializer is the serialization and deserialization of objects.

03. Serialize common fields of components

Common field types

Field construction method BooleanFieldBooleanField () NullBooleanFieldNullBooleanField () CharFieldCharField (max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) EmailFieldEmailField (max_length=None, min_length=None, allow_blank=False) RegexFieldRegexField (regex, max_length=None, min_length=None, allow_blank=False) SlugFieldSlugField (maxlength=50, min_length=None, allow_blank=False) regular field, verify the regular pattern [a-zA-Z0-9 -] + URLFieldURLField (max_length=200, min_length=None, allow_blank=False) UUIDFieldUUIDField (format='hex_verbose')

Format:

1) 'hex_verbose', such as "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"

2) 'hex', such as "5ce0e9a55ffa654bcee01238041fb31a"

3) 'int'-for example: "123456789012312313134124512351145145114"

4) urn' such as: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" IPAddressFieldIPAddressField (protocol='both', unpack_ipv4=False, * * options) IntegerFieldIntegerField (max_value=None, min_value=None) FloatFieldFloatField (max_value=None, min_value=None) DecimalFieldDecimalField (max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)

Max_digits: maximum digits

Decimal_palces: decimal point position DateTimeFieldDateTimeField (format=api_settings.DATETIME_FORMAT, input_formats=None) DateFieldDateField (format=api_settings.DATE_FORMAT, input_formats=None) TimeFieldTimeField (format=api_settings.TIME_FORMAT, input_formats=None) DurationFieldDurationField () ChoiceFieldChoiceField (choices)

The use of choices is the same as Django. MultipleChoiceFieldMultipleChoiceField (choices) FileFieldFileField (max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) ImageFieldImageField (max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL) ListFieldListField (child=, min_length=None, max_length=None) DictFieldDictField (child=)

Option parameters:

Name function max_length maximum length min_lenght minimum length allow_blank allowed empty trim_whitespace truncated white space character max_value maximum min_value minimum

General parameter

The parameter name description read_only indicates that the field is only used for serialization output, the default Falsewrite_only indicates that the field is only used for deserialization input, the default Falserequired indicates that the field must be entered when deserializing, the default value allow_null used by default Truedefault deserialization indicates whether the field is allowed to be passed into None, and the validator error_messages used by default Falsevalidators this field contains a dictionary of error number and error information label for HTML to display API pages The displayed field name help_text is used for HTML to display the field help prompt information when displaying the API page.

Here is an additional parameter, source, which is explained in the official documentation:

The name of the property that will be used to populate the field. It can be a method that accepts only the self parameter, such as URLField (source='get_absolute_url'), or you can use a dot symbol to traverse attributes, such as EmailField (source='user.email'). When serializing fields with dot semicolons, default may need to provide a value if any object does not exist or is empty during property traversal.

The value source='*' has a special meaning to indicate that the entire object should be passed to the field. This is useful for creating nested representations or for fields that need access to the full object to determine the output representation.

The default is the field name.

One of the more common uses:

1. Source= "get_field_name_display" as shown above, the explanation of the option can be shown in the choice field, where the usage represents the official explanation that can only accept the self parameter, that is, the source can fill in the methods that can be called by the serializer object (self is required in the method). The inherent logic is that this field will display the returned results of this method.

2. Source='user.email' is often used in subclasses of ModelSerializer, where user is a User object, which refers to displaying the email attribute of user. It is often used when we want to display the attribute of the foreign key object user at the same level as that of this object, rather than at the next level.

04. Serialization components is_valid, validated_data

When we define the serializer, how do we verify the incoming fields? That is the is_valid method, and you can determine whether the incoming field is legal according to the validation rules that define the serializer.

Serializer = CommentSerializer (data= {'email':' foobar', 'content':' baz'}) serializer.is_valid () # Falseserializer.errors# {'email': [' Enter a valid e-mail address.'], 'created': [' This field is required.']}

Serializer.validated_data can then get the validated data dictionary.

05. Serialization component check field

There are often three ways to serialize a component check field:

1. First, enter a list of verification methods in the validators attribute of the field, such as validators= (my_validator,) where the verification rules are defined in my_validator.

Def multiple_of_ten (value): if value% 10! = 0: raise serializers.ValidationError ('Not a multiple of ten') class GameRecord (serializers.Serializer): score = IntegerField (validators= [multiple _ of_ten])

2, the most commonly used is to define a validate_field_name (self, value) function (where field_name refers to the field name), the function is the specific logic.

From rest_framework import serializersclass BlogPostSerializer (serializers.Serializer): title = serializers.CharField (max_length=100) content = serializers.CharField () def validate_title (self, value): "" Check that the blog post is about Django. If 'django' not in value.lower (): raise serializers.ValidationError ("Blog post is not about Django") return value

3. The last one is to define a validate (self, data) where data is the key-value pair of all fields, so this verification method is an object-level check.

From rest_framework import serializersclass EventSerializer (serializers.Serializer): description = serializers.CharField (max_length=100) start = serializers.DateTimeField () finish = serializers.DateTimeField () def validate (self, data): "" Check that start is before finish. " If data ['start'] > data [' finish']: raise serializers.ValidationError ("finish must occur after start") return data

Of course, maybe when you see this, you'll ask why? How? Can only say that the source code is the best answer.

06. Serialize the component. Create () and .update ()

In our defined serialization class, we can add create and update methods. When we have a need to create a record or update a piece of data in the database table based on the deserialized data, we can define the corresponding logic in the create method and the update method.

Class CommentSerializer (serializers.Serializer): email = serializers.EmailField () content = serializers.CharField (max_length=200) created = serializers.DateTimeField () def create (self, validated_data): return Comment.objects.create (* * validated_data) def update (self, instance, validated_data): instance.email = validated_data.get ('email', instance.email) instance.content = validated_data.get (' content') Instance.content) instance.created = validated_data.get ('created', instance.created) instance.save () return instance

Then you can create a record or update a record by calling the serializer.save () command, which determines when the save is created and when it is updated. The key lies in the instantiation of serializer.

# .save () will create a new instance.serializer = CommentSerializer (data=data) serializer.save () # .save () will update the existing `comment` instance. Serializer = CommentSerializer (comment, data=data) serializer.save ()

The create method is called to create a record when no model object is passed in by the instantiation of the Serializer class, and the update method is called to update a record if the model object is passed in when the Serializer class is instantiated.

What if we sometimes need fields other than deserialized ones? We can pass the parameter name and value in save, and we can get the corresponding value in validated_data based on the parameter name.

Serializer.save (owner=request.user)

So we can get the user object in validated_data.get ("owner").

07. Serialization component ModelSerializer

The ModelForm components of ModelSerializer and the form are very similar, which greatly simplify our development. If you can define the corresponding model,ModelSerializer in the inner class Meta, you will automatically generate the Field corresponding to the model field without our definition.

Class AccountSerializer (serializers.ModelSerializer): class Meta: model = Account fields = ['id',' account_name', 'users',' created']

If all the fields are serialized in fields, write _ _ all__,. We do not define specific fields in the above example. ModelSerializer helps us to automatically generate the Field of 'id',' account_name', 'users',' created'.

08. Serialization components construct complex structures

Here is a serializer with one-to-many and many-to-many fields

Serializer

From res_framework import serializers# is used for instantiation. Many-to-many fields say class AuthorSerializer (serializers.Serializer): id = serializers.Charfield () name = serializers.Charfield () age = serializers.Charfield () # passed to views.py 's main class class BookSerializer (serializers.Serializer): name = serializers.Charfield () # source can specify the field, and id is the table name to be serialized. Id = serializers.CharField (source='nid') #, used for fields after source. Can be queried across tables. Publish = serializer.CharField (source='publish.email')''if you define a test method in the book class of models.py. Def test (self): the result returned by return str (self.price) + self.name''# will have a xx field. Souce can specify not only the table model field, but also the model table method, and assign values to the xx variable xx = serializers.Charfield (source='test') # how to implement the foreign key: # one-to-many fields # if you want to return all the information of the publisher through the foreign key field Including id,name,email... # obj is the data object that the current loop serializes to publish = serializers.SerializerMethodField () def get_publish (self,obj): return {'id':obj.publish.pk,'name':obj.publish.name} # many-to-many fields # details of all authors It also shows authors = serializers.SerializermethodFiled () def get_authors (self,obj): author_list = obj.authors.all () author_ser = AuthorSerializer (author_list,many=True) return author_ser.data

Views

From rest_framework.views import APIViewfrom rest_framework.response import Responsefrom app01 import modelsclass BookView (APIview): def get (self,request,*args,**kwargs): # get all book data response = {'status':100,'msg':' obtained successfully'} book_list = models.Book.objects.all () # instantiate the BookSerializer class Pass in the serialized data book_list # if you want to serialize the querySet object, be sure to add many=True book_ser = BookSerializer (book_list,many=True) # take out the serialized data book_ser.data and put it in the response dictionary and return it to the client response ['data'] = book_ser.data return Response (response)

If you use ModelSerializer:

Serializer

From app01 import modelsclass PublishSerializer (serializers.ModelSerializer): class Meta: # fixed writing # specify to serialize Book table model = models.Book # specify fields to serialize fields = ['nid','name'] # serialize all fields fileds =' _ all__' # fields to be excluded (cannot be used with fileds) # exclude = ['name' 'price'] # depth decision depth = 1 # if you don't follow the parent class If you want to define the displayed field yourself, define one that overrides the field properties of the parent class. Publish = serializers.SerializerMethodField () # one-to-many field def get_publish (self,obj): return {'id':obj.publish.pk,'name':obj.publish.name}

Here is an additional explanation for the parameter depth: in an object, another object has a foreign key, another object has a foreign key, and so on, the function of depth is to determine the depth of the foreign key when serializing.

The point of a complex serializer is the use of serializers.SerializerMethodField () and get_field_name to get the field values you want, as well as the use of source, as mentioned above.

09. Serialized component modifies the returned values to_representation and to_internal_value

To_representation (self, instance): if the serializer defines this method, you can change the value of the serialized object data, that is, the value of serializer.data, and you can reconstruct the return value according to your business scenario.

Def to_representation (self, instance): "Convert `username` to lowercase." Ret = super () .to_representation (instance) ret ['username'] = ret [' username'] .lower () return ret

To_internal_value (self, data): data is an unchecked data field. This method implements a checksum to modify the deserialized value, and then returns. If you don't want to modify the deserialized value just for verification, you can use the validate method instead.

Def to_internal_value (self, value): if value = = None: return 0 return value

In summary, one of the two methods is used to reconstruct the validated_data and return, and the other is used to reconstruct the value of the serializer.data and return.

After reading the above, do you have any further understanding of how to use the Django serialization component Serializers? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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