Django REST Framework学习-分页,通用视图,自定义RelatedField

使用通用视图+分页+自定义RelatedField


url:cardusers/pk/


传入模型Card的pk,获取当前Card的所有User中username和头像avatar,User是avatar的外键


1. 重载ListAPIView,加入分页

class UserSnapList(ListAPIView):


    paginate_by = 10
    paginate_by_param = 'page_c'
    serializer_class = UserSnapshoot
    model = User


    def get_object(self, pk):
        try:
            return Card.objects.get(pk=pk)
        except Card.DoesNotExist:
            raise Http404




    def get(self, request, *args, **kwargs):
        card = self.get_object(pk = kwargs.get('pk'))
        self.queryset = card.users.all()
        return super(UserSnapList, self).get(request, *args, **kwargs)

2. 自定义RelatedField

from django.contrib.auth import get_user_model

from avatar.models import Avatar
from avatar.util import get_default_avatar_url

from rest_framework import serializers



class PrimaryAvatarField(serializers.RelatedField):


    def field_to_native(self, obj, field_name):
        try:
            a_path = get_primary_avatar(obj, 30) 
            if a_path:
                return self.to_native(a_path.avatar_url(30, 30))
            else:
                return self.to_native(get_default_avatar_url())
        except Avatar.DoesNotExist:
            return self.to_native(get_default_avatar_url())

    def to_native(self, value):
        return value

class UserSnapshoot(serializers.ModelSerializer):

    avatar_set = PrimaryAvatarField(many = True)

    class Meta:
       model = get_user_model()
       fields = ('username', 'avatar_set')

效果图

Django REST Framework学习-分页,通用视图,自定义RelatedField_第1张图片


你可能感兴趣的:(django,pagination,rest_framework)