You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django ModelViewSet无法返回关联Department对象列表的问题

Django ViewSet返回关联Department列表的解决方案

1. 调整查询集

要获取所有关联Course的Department对象,需直接查询Department模型,筛选出存在关联Course的记录,同时避免重复返回同一Department:

queryset = models.Department.objects.filter(course__isnull=False).distinct()
  • filter(course__isnull=False):仅保留有对应Course的Department
  • distinct():确保每个Department仅出现一次(当多个Course关联同一Department时生效)

2. 替换序列化器

直接使用针对Department模型的DepartmentSerializer,因为现在要序列化的是Department对象而非Course。

修改后的完整ViewSet代码

class DepartmentFromCoursesViewSet(ReadOnlyModelViewSet):
    queryset = models.Department.objects.filter(course__isnull=False).distinct()
    serializer_class = my_serializers.DepartmentSerializer

可选调整

如果不需要去重(允许同一Department随关联Course重复出现),只需去掉.distinct()即可,但多数场景下建议保留去重逻辑。

内容的提问来源于stack exchange,提问作者Martin Kršek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:12:20