美文网首页
django rest framework 多对多数据报错

django rest framework 多对多数据报错

作者: whong736 | 来源:发表于2019-01-28 14:45 被阅读22次

    1.Model定义

    from django.db import models
    from datetime import datetime
    #引入系统用户的分类
    from django.contrib.auth.models import AbstractUser
    class Role(models.Model):
        """
        角色表
        """
        role_name = models.CharField(max_length=30, unique=True, verbose_name="角色名")
        create_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")
        role_desc = models.TextField(max_length=100, verbose_name="角色描述")
        role_parent_id = models.IntegerField(default=0, verbose_name="父级角色id")
        update_time = models.DateTimeField(default=datetime.now, verbose_name="更新时间")
    
        class Meta:
            verbose_name = "角色"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.role_name
    
    #userProfile继承AbstractUser分类,进行拓展
    class UserProfile(AbstractUser):
        """
        用户类拓展
        """
        name = models.CharField(max_length=30, verbose_name="姓名" )
        avatar = models.CharField(max_length=100, null=True, blank=True, verbose_name="头像")
        role = models.ManyToManyField(Role, verbose_name="角色", related_name='role', )
    
        class Meta:
            verbose_name = "用户"
            verbose_name_plural = verbose_name
    
        def __str__(self):
            return self.username
    
    

    2.Serializer 定义:

    # -*- coding: UTF-8 -*-
    from django.contrib.auth import get_user_model
    from users.models import Role
    from rest_framework import serializers
    User = get_user_model()
    
    
    class UserDetailSerializer(serializers.ModelSerializer):
        """
        用户详情序列表类
        """
        role = serializers.SlugRelatedField(
            many=True,
            read_only=True,
            slug_field='role_name'
         )
        class Meta:
            model = User
            fields = ("id", "username", "name", "role", "avatar")
            depth = 1
    
    
        def create(self, validated_data):
             print( validated_data)
             role_data = validated_data.pop["role"]
             # print(role_data)
             user = super(UserDetailSerializer, self).create(validated_data= validated_data)
             user.set_password(validated_data["password"])
             user.save()
             for role in role_data:
                 user.role.create(user=user, **role)
             return user
    

    3.View定义

    
    User = get_user_model()
    
    class UserViewset(CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        """
        用户
        """
        serializer_class = UserDetailSerializer
        queryset = User.objects.all()
    
    

    4#URL定义

    router = DefaultRouter()
    router.register(r'api/users', UserViewset, base_name="users")
    
    

    Postman

    image.png

    相关文章

      网友评论

          本文标题:django rest framework 多对多数据报错

          本文链接:https://www.haomeiwen.com/subject/gveajqtx.html