16-----用户与权限绑定

Drf 序列化 ModelSerializer跨表取数据,例子

1、对于OneToOne、Foreignkey、choices字段可以使用source取出相关信息:

class CourseSerializer(serializers.ModelSerializer):
    # choices字段
    degree = serializers.CharField(source='get_degree_display')
    # ForeignKey字段
    teacher = serializers.CharField(source='teacher.name')
    class Meta:
        model = Course
        fields = '__all__'

2、对于ManyToMany字段,例如:

class BookSerializers(serializers.ModelSerializer):
    authors  = serializers.SerializerMethodField()
    publisher = serializers.CharField(source='publisher.title')
    class Meta:
        model = Book
        fields = "__all__"  # 可选择显示字段
        # exclude = ['price',]  # 排除字段

    def get_authors(self,obj):
        query_set = obj.authors.all()
        return [{'name':obj.name} for obj in query_set]



{
    "id": 2,
    "authors": [
        {
            "name": "蒋勋"
        }
    ],
    "publisher": "长江出版社",
    "title": "蒋勋说唐诗",
    "pub_date": "2018-11-04",
    "word_count": 12,
    "price": 34
}

 本项目相关的

class UserSerializer(serializers.ModelSerializer):
    '''
    序列化 userporfile数据库
    '''
    roles = serializers.SerializerMethodField()   # 自定义设置的字段
    # 自动向内部进行深度查询  depth表示查询层数
    class Meta:
        model = UserProfile
        #fields ="__all__"

        fields = ['id','username','name','sex','email','avatar','addr','roles']
        # depth = 1  # 0 ~ 10  默认的depth为0

    # Drf 序列化 ModelSerializer跨表取数据
    def get_roles(self,obj):   # get_字段
        roles_query_set = obj.roles.all()
        return [{obj.name + ','} for obj in roles_query_set]    # 返回 roles 外表结果

 

posted @ 2020-04-12 13:15  王竹笙  阅读(285)  评论(0编辑  收藏  举报