'dict' object has no attribute 'pk' when using HyperlinkedIdentityField with optimized queryset #9430
Replies: 3 comments 4 replies
-
Have you tried changing the queryset optimisation to class CarViewSet(viewsets.ReadOnlyModelViewSet):
def get_queryset(self):
return Car.objects.all().only('pk') I think it would have the same effect as SELECT "vehicules_car"."id" FROM "vehicules_car" The resulting queryset will contain model instances, instead of dicts. |
Beta Was this translation helpful? Give feedback.
-
In my situation (more complex than this example), using def get_api_url(self, obj):
request = self.context.get('request')
abs_url = reverse('api:cars-detail', kwargs={"pk": obj['pk']})
return request.build_absolute_uri(abs_url) |
Beta Was this translation helpful? Give feedback.
-
I someone wondered how to include the object url without slowing down the api here is how i did it: def get_queryset(self):
"""Queryset is optimized for list or retrieve views"""
magic_key = 'magic_key'
abs_url = reverse('api:accidents-detail', kwargs={"pk": 'magic_key'})
full_url = self.request.build_absolute_uri(abs_url)
return Car.objects.annotate(
api_url=Replace(Value(full_url), Value(magic_key), Cast(F('pk'), output_field=CharField()), output_field=CharField())
).values(
'api_url',
) I build the url wich is a rather slow process only once, then proceed in SQL to replace the part corresponding to the actual objet id. |
Beta Was this translation helpful? Give feedback.
-
HyperlinkedIdentityField
may not work with optimized querysets using.values()
.Let our model be a Car:
Our Serializer:
and viewset:
then i obtain this error
'dict' object has no attribute 'pk'
because theget_url
django-rest-framework/rest_framework/relations.py
Line 321 in fbdab09
HyperlinkedIdentityField
is expecting a model instance, not a dict.Tested with DRF 3.15.1
Seems to be an issue to me, but i followed the guidelines and asked it here first. What do you think .
If i get your approval i will go on and create an issue, i can even work on a PR.
Beta Was this translation helpful? Give feedback.
All reactions