您的位置:首页 > 编程语言 > Go语言

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

2014-03-23 17:24 232 查看
使用通用视图+分页+自定义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')


效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息