rest_framwork serialization Serializer and ModelSerializer, url generation HyperlinkedIdentityField, depth depth

Serializer:

  Custom error message type field provided error_messages value

  SerializerMethodField field type for the custom field value display, the method needs to construct a field value of the return, the return value may be a list, dictionaries, strings, numbers and the like: get_ Field Name

  Custom display can be screened for the return value manipulation SerializerMethodField

  soure parameters for customizing the display: Using the most suitable in relation field

  Parameter validators receiving a list, a list of instances of objects stored class verification, the user determines POST, PUT request is data compliant

class PriceValidator:
     DEF  the __init__ (Self, Base): 
        self.base = Base 

    DEF  the __call__ (Self, value):
         IF value =! self.base: 
            Message = ' price must be greater than S%. ' % self.base
             The raise serializers.ValidationError (the Message) 

    DEF set_context (Self, serializer_field):
         "" " 
        This Hook at The iS Called by the Serializer instance, 
        prior, to being at The call validation Made. 
        " "" 
        # call before executing verification, serializer_fields the current field object 
        pass


class BookSerializers (serializers.Serializer): 
    title = serializers.CharField (error_messages, = { ' required ' : ' title can not be empty ' }) 
    . price = serializers.IntegerField (error_messages, = { ' required ' : ' the price can not be empty ' } , validators = [PriceValidator ( ' 18 is ' )])
     # publish = serializers.CharField (Source =' publish.name ') # many fields 
    publish = serializers.SerializerMethodField (error_messages, = { ' required ' : 'Press can not be empty '})   # Ways to customize the display 
    # publish_id = serializers.IntegerField () 
    pub_date = serializers.DateTimeField ()
     # the authors = serializers.CharField (Source = "authors.all") # field may take many to many objects with all corresponding All 
    the authors serializers.SerializerMethodField = ()   # ways to customize the display 

    # custom publish information display field, the method must be SerializerMethodField 
    DEF get_publish (self, obj):   # obj is the object of this book 
        DATA_LIST = {
             " ID " : obj.publish.id ,
             " name " : obj.publish.name,
             " Email ": Obj.publish.email 
        } 
        return DATA_LIST 

    DEF get_authors (Self, obj): 
        AUTHORS_LIST = [] 
        authors_queryset = obj.authors.all () filter (age__lt = 30).   # Book all authors, and younger than 30 years old 
        for author in authors_queryset: 
            authors_list.append (author.name) 
        return AUTHORS_LIST

 

ModelSerializer:

  Serializer difference and that the former manual, automatic latter. Metaclass only need to configure the remaining custom settings with no difference between the Serializer, e.g. source parameter, SerializerMethodField use are the same.

class PriceValidator:
     DEF  the __init__ (Self, Base): 
        self.base = Base 

    DEF  the __call__ (Self, value):
         IF value =! self.base: 
            Message = ' price must be greater than S%. ' % self.base
             The raise serializers.ValidationError (the Message) 

    DEF set_context (Self, serializer_field):
         "" " 
        This Hook at The iS Called by the Serializer instance, 
        prior, to being at The call validation Made. 
        " "" 
        # call before executing verification, serializer_fields the current field object 
        pass

class BookSerializers (serializers.ModelSerializer): 
    the authors = serializers.SerializerMethodField ()   # method of displaying the custom 
    # publish = serializers.CharField (Source = 'publish.name') # many fields 
    publish serializers.SerializerMethodField = ()   # method from Custom display 
    # Role = serializers.CharField (Source = "get_type_display") 
    class Meta -: 
        Model = models.Book
         # fields = "__all__ is" # default serialization all fields 
        fields = [ ' title ' , ' . price ' , ' publish ' ,' The authors ' ] 
     # custom error message 
        extra_kwargs = {
                     ' title ' : { " error_messages, " : { " required " : " Title can not be empty " }},
                     ' publish ' : { " error_messages, " : { " required " : ' Press not be empty ' }},
                     ' . price " : { "error_messages": { " Required " : ' the price can not be empty ' }, " validators " : [PriceValidator ( ' 18 is ' )]} 
                } 

    # custom publish field displays information, must SerializerMethodField method 
    DEF get_publish (Self, obj):   # obj this book is an object 
        DATA_LIST = {
             " the above mentioned id " : obj.publish.id,
             " name " : obj.publish.name,
             " Email " : obj.publish.email
        }
        return data_list

    DEF get_authors (Self, obj): 
        AUTHORS_LIST = [] 
        authors_queryset = obj.authors.all () filter (age__lt = 30).   # book all authors, and younger than 30 years old 
        for author in authors_queryset: 
            authors_list.append ( author.name) 
        return AUTHORS_LIST
class BookView (viewsets.ModelViewSet): 
    authentication_classes = [utils.Authentication,]   # authentication component, a list of categories based authentication discharge 
    permission_classes = [utils.PermissionCheck,]   # purview component, a list, the list discharge permission class 
    throttle_classes = [utils.VisitThrottle,]    # frequency component 
    from rest_framework.parsers Import JSONParser, MultiPartParser, FormParser 
    parser_classes = [JSONParser, MultiPartParser, FormParser]   # parser 
    QuerySet models.Book.objects.all = ()   # QuerySet objects 
    serializer_class = serializers.BookSerializers   # serialization class

 

HyperlinkedIdentityField:生成url

re_path('^publish/(?P<pk>\d+)', views.PublishDetailView.as_view(), name='publish_detail'),
path('book/', views.BookView.as_view({'get': 'list', 'post': 'create'}),),
class BookSerializers(serializers.ModelSerializer):
    publish = serializers.HyperlinkedIdentityField(view_name="publish_detail", lookup_field='publish_id', lookup_url_kwarg='pk')
     class Meta:
        model = models.Book
        # fields = "__all__"  # 所有字段默认序列化
        fields = ['title', 'price', 'publish', 'authors']

        extra_kwargs = {
                     ' title ' : { " error_messages, " : { " required " : " Title can not be empty " }},
                     " publish " : { " error_messages, " : { " required " : " Press can not be empty ' } },
                     ' . price ' : { " error_messages, " : { "required": ' Prices can not be empty ' }, " validators " : [PriceValidator ( ' 18 is ' )]} 
                }

 

depth:

  Relationship Relationship relationship field field number field in the layer, i.e., the relationship between a field for displaying a relationship field ......

class BookSerializers(serializers.ModelSerializer):
    # authors = AuthorsSerializers(many=True)

    class Meta:
        model = models.Book
        # fields = ["title", "price", "publish_id", "pub_date", "authors"]
        fields = "__all__"
        extra_kwargs = {
            'title': {"error_messages": {"required": "书名内容不能为空"}},
            'publish': {" Error_messages, " : { " required " : ' Press not be empty ' }},
             ' . Price ' : { " error_messages, " : { " required " : ' the price can not be empty ' }} 
        } 
        # depth =. 1 Table # Get the many-depth field

 

Guess you like

Origin www.cnblogs.com/aizhinong/p/12563203.html