我在ModelViewSet中覆盖get_queryset以支持“me”作为过滤器和多个pk搜索:
class UserViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get_queryset(self):
qs = UserProfile.objects.all()
if 'pk' in self.kwargs:
pk_user = self.kwargs['pk']
if ',' in pk_user: # Multiquery
pk_users = pk_user.split(',')
qs = qs.filter(pk__in=pk_users)
elif pk_user == "me":
qs = qs.filter(pk=self.request.user)
else:
qs = qs.filter(pk=pk_user)
# By default return all the items
return qs
我正在使用以下序列化程序:
class UserProfileSerializer(serializers.ModelSerializer):
avatar_thumbnail_small = serializers.ImageField(read_only=True)
avatar_thumbnail_medium = serializers.ImageField(read_only=True)
id = serializers.CharField(source='user.id')
username = serializers.CharField(source='user.username')
firstname = serializers.CharField(source='user.first_name')
lastname = serializers.CharField(source='user.last_name')
class Meta:
model = UserProfile
fields = ('id', 'username', 'firstname', 'lastname', 'karma', 'avatar_thumbnail_small', 'avatar_thumbnail_medium', 'contacts', 'suggested_contacts')
我在urls.py中注册了网址
router = routers.DefaultRouter()
router.register(r'users', app.views_rest.UserViewSet, base_name="users")
但当我尝试获取url / api / users / 2,3 /或/ api / users / me /时,它会显示一条json消息,指出未找到详细信息。
/ api / users / 2 /,/ api / users / 3 /和/ api / users /工作正常。
感谢您的帮助。
答案 0 :(得分:1)
这不起作用,因为检索操作之后也会调用get_object
并且您没有覆盖它。见https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L76