1👍
✅
This is expected behavior for StringRelatedField()
The StringRelatedField
returns the str
representation of the value and in your case, the user is having an integer value. If you were using the QuerySet
(without calling the values()
), the user will have a User
instance and thus the str
representation will give you the proper result.
You had felt a performance improvement because the values('id', 'location', 'user', )
fetching the values from a single table (note that, calling user
will not make an inner join here) and there is no chance for an N+1
problem. But, if you were using the User’s str
method, Django will make an inner join and there will be an N+1
problem and thus you will have performance issues.
So, you have two options,
- Use values and ignore the
User
‘s representation - Use
select_related()
class ReportViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = ReportReadSerializer
def get_queryset(self):
some_other_model = get_object_or_404(Organization, pk='some_other_model_id')
return Report.objects.filter(
location__within=some_other_model.region
).select_related("user")
👤JPG
Source:stackexchange.com