I have models (one user can has multiple employees):
from django.db import models
class User(models.Model):
username = ...
first_name = ...
last_name = ...
class OrgUnit(models.Model):
name = ....
address = ...
class Employee(models.Model):
personnel_no = ...
user = models.ForeignKey(User, related_name='employees'...)
orgunit = models.ForeignKey(OrgUnit, ...)
Serializers and views:
class EmployeeSerializer(serializers.ModelSerializer):
orgunit = serializers.CharField(source='orgunit.name') <==== one orgunit - one query to DB
class Meta:
model = Employee
fields = '__all__'
class CustomUserSerializer(serializers.ModelSerializer):
employees = EmployeeSerializer(many=True)
class Meta:
model = User
fields = '__all__'
class UsersViewSet(ViewSet):
def me(self, request):
serializer = CustomUserSerializer(request.user)
return Response(serializer.data)
When serializing orgunit.name per one orgunit one query to DB is being performed. How to avoid this? How to prefetch employees related_name and its orgunits?