postgresql 无法从ModelViewSet内的所有父对象中检索子对象

gab6jxml  于 2023-03-17  发布在  PostgreSQL
关注(0)|答案(1)|浏览(118)

这些是我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接收此对象.

r1wp621o

r1wp621o1#

不确定这是否是最佳方法,但这是有效的:

class DepartmentFromCoursesViewSet(ReadOnlyModelViewSet):
   serializer_class = serializers.DepartmentSerializer

   def get_queryset(self):
      # Get all unique IDs of Departments from all Course
      department_ids_set = set(models.Course.objects.all().values_list('department_id', flat=True))
      # Get all Departments filtered by IDs
      return models.Department.objects.filter(id__in=department_ids_set)

相关问题