RESTFrame serialization problem

Serialization has two main functions:
1. It is used to verify user request data;

2. Serialize the data in the database (queryset type, model object).

1. Serialize the data (queryset, model object) obtained by the back-end program from the database

models.py # Preparation: table structure

from django.db import models

class Menu(models.Model):
    name = models.CharField(max_length=32)

class Group(models.Model):
    title = models.CharField(max_length=32)
    mu = models.ForeignKey(to='Menu',default=1)

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

    group = models.ForeignKey('Group')
    roles = models.ManyToManyField('Role')


class Role(models.Model):
    name = models.CharField(max_length=32)

The following is part of the view

########### 1. Serialize according to the model table #######################

class UserSerializer(serializers.ModelSerializer):   # 继承自ModelSerializer类
    '''Class of serialized data, get fields according to model table'''
    x1 = serializers.CharField(source='name') # custom field, must define source
    class Meta:
        model = models.UserInfo
        # fields = '__all__'
        fields = ['name','pwd','group','x1']
        depth = 3 # This field means viewing data of several layers of nesting, it is not recommended to be too large, performance loss


class UserView(APIView):
    '''User-Related Views'''

    def get(self,request,*args,**kwargs):
        user_list = models.UserInfo.objects.all() # query type data obtained from the database
        ser = UserSerializer(instance=user_list,many=True) # Serialized class, get an object
        print(ser.data) # Serialized data in json format
        return Response(ser.data)
####### 2. Define which fields to be serialized include: single table, one-to-many, many-to-many relationship ###########

class MyCharField(serializers.CharField):
    "The class that needs to serialize the field in the custom template is to customize the return value in the many-to-many relationship"
    def to_representation(self, value):
        # value represents the object associated with the current user object
        role_list = []
        for each in value:
            role_list.append(each.name)
        return role_list

# Create a class that inherits from serializers.Serializers, which needs to define the fields that need to be serialized
class UserSerializer(serializers.Serializer):
    "Equivalent to creating a serialized template to specify the required fields"
    # Fields in a single table
    id = serializers.CharField() # obj.id (If source=xxx is not written, obj.id will be executed)
    name = serializers.CharField()
    pwd =serializers.CharField()

    #Query across tables (many to one)
    group = serializers.CharField(source='group.title') # The source gets the group attribute of the current object,
    menu_ttile = serializers.CharField(source='group.mu.name')
    menu_id = serializers.CharField(source='group.mu.id') # Judge inside the string, if it can be executed, it will be executed

    # Many-to-many (customize the content returned after the current field is serialized)
    # role_list = serializers.CharField(source='roles.all')
    # This, in the final display, can only be made like this "role_list": "<QuerySet [<Role: Role object>, <Role: Role object>]>"

    # Method 1: Customize the to_representation method
    # For the above case, customize the return value, inherited from (serializers.CharField)
    # role_list = MyCharField(source='roles.all') # Look at the custom class MyCharField above, which rewrites the to_representation method

    # Method 2: (In fact, the returned content still needs to customize the returned value of the MyCharField() class, but the value specifies each role object,)
    # role_list = serializers.ListField(child=serializers.CharField(),source='roles.all')

    # Method 3: (You also need to customize the get_field name, define the return value of this subfield, better customization, =====recommended to use ====)
    role_list = serializers.SerializerMethodField()

    def get_role_list(self,obj):# obj is the current user object
        li = []
        roles_list = obj.roles.filter(id=1) # Filter information can be added here
        roles_list = obj.roles.all()
        for i in roles_list:
            li.append({'id':i.id,'name':i.name})
        return li



class UserView(APIView):

    def get(self,request,*args,**kwargs):
        user_list = models.UserInfo.objects.all() # Data obtained from the database
        ser = UserSerializer(instance=user_list,many=True)
        print (ser.data)
        return Response(ser.data)

2. Verify the database submitted by the front-end POST, similar to form verification

This is also two cases, similar to serialization, one is done according to the table, the other is refined to the field

########## Serialization function 2: verify the request data #############################


class PassworValidator():
    '''Authentication rule class for custom authentication passwords'''
    def __init__(self, base): # base, is the validation rule, which can be defined as a regular expression, or a function.
    # def __init__(self): # base, is the validation rule, which can be defined as a regular expression, or a function.
        self.base = base


    def __call__(self, value): # When called, the __call__ method will be executed, and value is the data submitted by the previous post
        '''Do the validation in this function, then return '''
        print(value,'value's value is')
        if value != self.base:
        # if value != 1:
            message = 'This field must be %s'%self.base
            raise serializers.ValidationError(message) # The error thrown here will be received by ser.errors and displayed to the user




# The first type: If it is a serialized class defined by yourself (choose one of the validation classes below)
class UserSerializer(serializers.Serializer):
    name = serializers.CharField(min_length=5)
    pwd = serializers.CharField(error_messages={'required':'password cannot be empty'},validators=[PassworValidator('666'),]) # 666 here is the validation rule, you can also not write it, directly in the above class write in the __call__ method


# The second: serialization class directly inherited from the modelSerializer class (choose one with the validation class above)
class UserSerialazer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"


        # Define the validation rules for the fields
        extra_kwargs = {
            'name':{'min_length':3},
            'pwd':{'validator':[PassworValidator('666')],} # In PassworValidator, you can pass parameters or not.
        }


class UserView(APIView):


    def get(self,request,*args,**kwargs):
        user_list = models.UserInfo.objects.all()
        ser = UserSerializer(instance=user_list,many=True)
        print (ser.data)
        return Response(ser.data)


    def post(self,request,*args,**kwargs):
        ser = UserSerializer(data=request.data) # Generate an object
        if ser.is_valid():
            ret = ser.data # ser.data is the ReturnDict type, which inherits from OrderedDict, which inherits from dict
            ret = ser.validated_data # ser.data is the ReturnDict type, which inherits from OrderedDict, which inherits from dict
        else:
            print (ser.errors)
            print(ser.error_messages)
        return Response('POST request, corresponding content')


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325416776&siteId=291194637