#object.all in queryset?

11 messages · Page 1 of 1 (latest)

versed hornet
#

I was wondering do we need to query all the Users for DELETE/GET/PATCH operations?

class UserDetailView(generics.RetrieveUpdateDestroyAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_url_kwarg = 'user_id'
    lookup_field = 'user_id'

how can we query users by just the user_id in the queryset, and is this a correct approach?

novel schooner
#

Querysets are lazily evaluated. That means that just because you call User.objects.all() Django does not actually fetch data from the DB. The view classes do require a queryset, so this approach is indeed correct. The view will then call its own get_object() method, generate the appropriate SQL (e.g. select * from users where user_id=42;), and only get the relevant data.
The get_object method is inherited from GenericAPIView.
https://www.cdrf.co/3.14/rest_framework.generics/RetrieveUpdateDestroyAPIView.html

wicked oyster
#

U can also try this code class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
serializer_class = UserSerializer
lookup_url_kwarg = 'user_id'
lookup_field = 'user_id'

def get_queryset(self):
    user_id = self.kwargs.get('user_id')
    return User.objects.filter(user_id=user_id)
#

@novel schooner tell me if it works

novel schooner
# wicked oyster <@1137652993609707540> tell me if it works

I don't see why it wouldn't, but it's also completely unnecessary. I'd have to look at the generated SQL to see if the ORM is smart enough to see how redundant the filter call is when get_object already calls get_object_or_404 with the exact same parameters 🤔

#

But at first glance, in pseudo-ish SQL, you are asking select * from users where user_id=42 from (select * from users where user_id in (42));

full bear
novel schooner
full bear
novel schooner
#

No need to override anything as OP has it correctly 😄