zoukankan      html  css  js  c++  java
  • DRF(Django Rest Framework)备忘

    ProjectType.objects.values('code').distinct() ProjectType表中code字段所有的值(不包含重复的值)

    三层嵌套serializers时。有可能报错“没有这个属性”,可以添加source='issue_set'这种方式。

    class MyProjectSerializer(serializers.ModelSerializer):
        """
        项目表:我的借款
        """
        issue = IssueSerializer(source='issue_set', many=True)
    

    反向取值

    class Member(AbstractUser):
    name = models.CharField(max_length=30, null=True, blank=True, verbose_name=u'用户名', unique=True)
    password = models.CharField(max_length=100, null=False, verbose_name=u'密码')
    class MemberIDCard(models.Model):
    member = models.OneToOneField(Member, verbose_name=u"会员", null=True, related_name="id_card")
    id_no = models.CharField(max_length=30, verbose_name=u'身份证号')

    SerializerMethodField 的一种方式
    is_recently = serializers.SerializerMethodField(method_name="method_is_recently")
    def method_is_recently(self, obj):
    pass

    class MemberOfLoginSerializer(serializers.ModelSerializer):
    """
    登录后返回的member信息
    """
    id_no = serializers.ReadOnlyField(source='id_card.id_no')
    class Meta:
    model = Member
    fields = ('id', 'real_name', 'mobile', 'id_no')

    class UserViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user
    

    @api_view(['GET'])
    def current_user(request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data)

    class CurrentUserView(APIView):
    def get(self, request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data).

    @api_view(['GET'])
    def current_user(request):
    user = request.user
    return Response({
    'username': user.username,
    'email': user.email,
    ...
    })

    class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        pk = self.kwargs.get('pk')
    
        if pk == "current":
            return self.request.user
    
        return super(UserViewSet, self).get_object()
    

    class UserViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user
     
     
  • 相关阅读:
    MQTT协议的简单介绍和服务器的安装
    Scrollview 嵌套 RecyclerView 及在Android 5.1版本滑动时 惯性消失问题
    gradle 命令
    git 命令学习
    PHP、JAVA、C#、Object-C 通用的DES加密
    JS中树形对象与数组之间的相互转换
    Javascript中的类型转换
    Javascript中的基本数据类型,如何判断数据类型,作用域链的理解
    前端面试题集锦(二)之CSS部分
    前端面试题集锦(一)之HTML部分
  • 原文地址:https://www.cnblogs.com/jeff-ideas/p/10540330.html
Copyright © 2011-2022 走看看