Custom fields in the setup sequence of the class

Custom fields in the setup sequence of the class

1. The field has choices for the property usage

This is a format type field dictionary type, stored in the database key, to the client to display the corresponding value, but normal operation can only read the database key, get value, when the need to use this source method.

Note
the format: Source = 'the get_ field names extracted _display', to display the value

class UserInfoSerializer(serializers.Serializer):
    user_type = serializers.CharField(source='get_user_type_display')

2. For the foreign key usage

If we need specific field information obtained in this category class foreign key, then the source will be needed by the class method in the sequence, slightly different formats.

Note
the format: Source = 'foreign keys defined in this class obtained desired field name.'
Foreign key name associated with this class of the object instance is essentially the foreign key can be obtained by way of the object attribute.

class UserInfoSerializer(serializers.Serializer):
    group = serializers.CharField(source='usergroup.title')

3. usage for many relationships

Many relationship, if the second embodiment which to write code obtained with less specific field information, the name of the foreign key .all of this class is defined in a list obtained by the specific objects, if desired to obtain the corresponding specific information for each object field, need to customize functions performed

Note

  • Field type must be:. Serializers SerializerMethodField ()
  • Function arguments to pass from the row, by row. .All associated field name () acquires the information associated with all the objects in multiple
class UserInfoSerializer(serializers.Serializer):
    role = serializers.SerializerMethodField()
    
    def get_role(self, row):
        row_obj_list = row.role.all()
        # 获取到对应的所有对象列表
        ret = {}
        for item in row_obj_list:
            ret[item.id] = item.title
            # 由于获得的是一个对象列表,所以我们需要遍历出每一个对对象,再通过对象来获得每一个字段信息
        return ret

Guess you like

Origin www.cnblogs.com/ddzc/p/12145668.html