Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RetrieveAPIView without lookup field?

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?

like image 786
merry-go-round Avatar asked Sep 28 '17 12:09

merry-go-round


1 Answers

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
like image 97
Brown Bear Avatar answered Nov 03 '22 21:11

Brown Bear