如何使用Django REST Framework根据组织ID获取关联的所有部门
根据组织ID获取关联部门的DRF实现方案
嘿,我来帮你搞定这个需求!首先得先把模型之间的关联建立起来——现在你的Organization和Departments是完全独立的,没有任何关联关系,所以第一步就是给部门模型加一个外键指向组织:
1. 修正模型关联
修改你的Departments模型,添加外键字段关联Organization:
from django.db import models class Organization(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Departments(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) email = models.CharField(max_length=30, unique=True) phone = models.CharField(max_length=20) # 补全你之前未写完的字段定义 organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="departments" # 方便从组织反向查询下属部门 )
这里的related_name设置为departments,之后你可以通过organization.departments.all()直接获取某个组织下的所有部门,非常便捷。
2. 创建序列化器
接下来编写DRF的序列化器,用来序列化部门数据。你可以根据需求选择两种序列化方式:
from rest_framework import serializers from .models import Organization, Departments # 仅序列化部门数据的序列化器 class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Departments fields = "__all__" # 也可以指定具体字段,比如['id', 'name', 'email', 'phone'] # 嵌套序列化:同时返回组织信息+下属所有部门 class OrganizationWithDepartmentsSerializer(serializers.ModelSerializer): departments = DepartmentSerializer(many=True, read_only=True) class Meta: model = Organization fields = ['id', 'name', 'description', 'departments']
3. 编写视图逻辑
这里提供两种实现方案,你可以根据实际需求选择:
方案一:仅返回指定组织下的部门列表
用ListAPIView重写查询逻辑,过滤出目标组织的部门:
from rest_framework.generics import ListAPIView from .models import Departments from .serializers import DepartmentSerializer class DepartmentListByOrgView(ListAPIView): serializer_class = DepartmentSerializer def get_queryset(self): # 从URL参数中获取组织ID org_id = self.kwargs.get('org_id') # 过滤出属于该组织的所有部门 return Departments.objects.filter(organization_id=org_id)
方案二:返回组织详情+关联的所有部门
如果需要同时展示组织信息和下属部门,用RetrieveAPIView配合嵌套序列化器:
from rest_framework.generics import RetrieveAPIView from .models import Organization from .serializers import OrganizationWithDepartmentsSerializer class OrganizationWithDepartmentsView(RetrieveAPIView): queryset = Organization.objects.all() serializer_class = OrganizationWithDepartmentsSerializer
4. 配置URL路由
最后在项目的urls.py中添加对应的路由规则:
from django.urls import path from .views import DepartmentListByOrgView, OrganizationWithDepartmentsView urlpatterns = [ # 方案一路由:访问 /api/organizations/1/departments/ 获取ID为1的组织的所有部门 path('api/organizations/<int:org_id>/departments/', DepartmentListByOrgView.as_view(), name='org-departments'), # 方案二路由:访问 /api/organizations/1/ 获取ID为1的组织详情及其所有部门 path('api/organizations/<int:pk>/', OrganizationWithDepartmentsView.as_view(), name='org-with-departments'), ]
这样就完成啦!测试的时候直接请求对应的URL,就能拿到你想要的关联数据了。
内容的提问来源于stack exchange,提问作者niran
相关产品推荐
相关产品推荐

