我有两个模型组织和部门。我想通过使用DRF得到所有部门相关的特定组织ID,我该怎么做
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=30)
org_linked=models.ForeignKey(Organization)
user_linked=models.ForeignKey(User)
class OrganizationAndDepartmentSerializer(serializers.ModelSerializer):
org_department=facilitesntSerializer(many=True)
class Meta:
model = facilites
fields=('org_department',)
class OrganizationAndDepartmentViewSet(viewsets.ModelViewSet):
serializer_class =OrganizationAndDepartmentSerializer
答案 0 :(得分:0)
如果你想要完整的嵌套表示;声明一个嵌套的序列化器,如下所示:
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Departments
fields = ('__all__')
class OrganizationSerializer(serializers.ModelSerializer):
departments = DepartmentsSerializer(many=True, source='org_linked_set', read_only=True)
class Meta:
model = Organization
fields = (
'name',
'description',
'departments'
)