RetrieveAPIView without lookup field?

2019-06-17 06:01发布

问题:

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:

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