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