I am looking to list out all of the teachers in a certain department in Django rest framework and am unsure of how to do so. I believe this would be done by adding a field to the Department serializer but I am not sure. Is there an easy way of how this can be done.
models.py
class Department(models.Model):
name = models.CharField(max_length=300)
def __str__(self):
return self.name
class Teacher(models.Model):
name = models.CharField(max_length=300)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
tenure = models.BooleanField()
serializers.py
class DepartmentSerializer(serializers.HyperlinkedModelSerializer):
#What I believe the serializer field would look like to list teachers connected
#with a department
teacher = serializers.DjangoModelField(
Teacher.objects.filter(department=self.department))
class Meta:
model = Department
fields = ['url', 'name', 'teacher']
urls.py
router = DefaultRouter()
router.register(r'teachers', TeacherViewSet)
router.register(r'departments', DepartmentViewSet)
router.register(r'users', UserViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
views.py
class TeacherViewSet(viewsets.ModelViewSet):
queryset = Teacher.objects.all()
serializer_class = TeacherSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
class DepartmentViewSet(viewsets.ModelViewSet):
queryset = Department.objects.all()
serializer_class = DepartmentSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
CodePudding user response:
You can access the Teacher
s linked to a department
with mydepartment.teacher_set.all()
, we can use that in the serializer like:
class TeacherSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Teacher
fields = ['name', 'tenure']
class DepartmentSerializer(serializers.HyperlinkedModelSerializer):
teacher_set = serializers.TeacherSerializer(many=True)
class Meta:
model = Department
fields = ['url', 'name', 'teacher_set']