RetrieveAPIView without lookup field?

2019-06-17 05:40发布

By default RetrieveAPIView or RetrieveUpdateAPIView requires lookup_field to retrieve Model.

However in my case, I want to retrieve my model by self.request.user.

Here is views.py example

class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileRetrieveAndUpdateSerializer
    lookup_field = 'user_id'

    def get_queryset(self):
        qs = Profile.objects.all()
        logged_in_user_profile = qs.filter(user=self.request.user)
        return logged_in_user_profile

Can I use RetrieveAPIView without lookup_field?

1条回答
SAY GOODBYE
2楼-- · 2019-06-17 06:23

You need override get_object

def get_object(self):
  queryset = self.get_queryset()
  obj = get_object_or_404(queryset, user=self.request.user)
  return obj
查看更多
登录 后发表回答