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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With