这些是我Django项目中的类。
### Models ###
class Course(models.Model):
department = models.ForeignKey(Department, on_delete=models.CASCADE, null=True)
class Department(models.Model):
name = models.CharField(max_length=300)
### Serializers ###
class DepartmentFromCourseSerializer(serializers.ModelSerializer):
department = my_serializers.DepartmentSerializer()
class Meta:
model = models.Course
fields = ('id', 'department')
### ViewSets ###
class DepartmentFromCoursesViewSet(ReadOnlyModelViewSet):
queryset = models.Course.objects.select_related('department')
serializer_class = serializers.DepartmentFromCourseSerializer
我从我的DepartmentFromCoursesViewSet收到的是以下响应:
{
"count": 500,
"next": "https://...",
"previous": null,
"results": [
"id": 1
"department": {
"id": 150,
"name": "My department1"
},
"id": 2
"department": {
"id": 151,
"name": "My department2"
}
]}
但我想得到的是所有课程的部门对象的列表。
"count": 500,
"next": "https://...",
"previous": null,
"results": [
{
"id": 150,
"name": "My department1"
},
{
"id": 151,
"name": "My department2"
}
]}
我知道我需要将串行器更改为DepartmentSerializer,其中将包含 meta:model=models.Department and fields=('id ',' name ').但我无法从ViewSet接收此对象.
1条答案
按热度按时间r1wp621o1#
不确定这是否是最佳方法,但这是有效的: