我正在创建一个 REST API 来为 Android 应用程序提供服务。我不是要重新发明轮子,所以我尝试使用在 https://github.com/revsys/django-friendship/ 找到的 django-friendship 应用程序结合 DRF。不幸的是,django-friendship 的文档相当稀少,而且我是 Django/DRF 开发的新手。我遇到了无法查看基于个人的好友关系的问题。
好友 ListView 应显示请求用户的所有好友。我可以在单独的 View 上创建 friend ,但该 View 会显示每个 friend 关系。我希望能够查看特定用户的好友。也就是说,当用户获取/friends/目录时,它将显示他们的好友列表。
但是,现在这个 View 只显示一个空的 JSON 对象,而不是用户的好友列表。我应该如何更改我的 FriendList View ,以便它正确地返回用户的好友列表?
View .py
class FriendList(APIView):
"""
Lists all of the requesting users friends
"""
def get(self, request):
friends = Friend.objects.friends(request.user)
serializer = FriendSerializer(friends, many=True)
return Response(serializer.data)
序列化器.py
class FriendSerializer(serializers.ModelSerializer):
class Meta:
model = Friend
网址.py
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
url(r'^api-token-auth/', obtain_auth_token),
url(r'^friends', views.FriendList.as_view())
最佳答案
def get(self, request):
friends = Friend.objects.friends(request.user)
在上面的代码中,您可能希望使用 get()
或 filter()
而不是 friends()
关于python - Django Rest Framework View 返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249855/