我有一个可以列出几座建筑物的API。每个建筑物都属于几个建筑物组,每个建筑物组包含几个建筑物。
我想显示一个建筑组的单个字段。更具体地说,我想在RetrieveAPIView中显示一个建筑物组的所有建筑物。
我可以使用通用视图列出单个BuildingGroup实例,如下所示:
class BuildingGroupRetrieveAPIView(RetrieveAPIView):
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.buildings.all()
我假设我可以覆盖get方法以仅显示该检索到的对象的单个字段。具体来说,我想显示我多对多关系中的所有对象。或更确切地说,我想检索我的m2m关系中的所有完整数据。
这是我的模特:
class Building(models.Model):
name = models.CharField(max_length=120, null=True, blank=True)
def __str__(self):
return self.name
class BuildingGroup(models.Model):
description = models.CharField(max_length=500, null=True, blank=True)
buildings = models.ManyToManyField(Building, default=None, blank=True)
我尝试了这个但没有成功:
def get(self):
building_group = BuildingGroup.objects.get(id='id')
qs = building_group.buildings.all()
return qs
我的序列化器
class BuildingGroupSerializer(serializers.ModelSerializer):
class Meta:
model = BuildingGroup
fields = (
'description',
.....
)
我可以附加屏幕截图以使其更加清晰。
我们非常感谢您的帮助。预先感谢
Here is my full view:
class BuildingGroupAPIView(ListAPIView):
permission_classes = [permissions.IsAdminUser]
authentication_classes = [SessionAuthentication]
serializer_class = BuildingGroupSerializer
passed_id = None
def get_queryset(self):
qs = BuildingGroup.objects.all()
query = self.request.GET.get('q')
if query is not None:
qs = qs.filter(name=query)
return qs
class BuildingGroupRetrieveAPIView(RetrieveAPIView):
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.buildings.all()
def get(self):
building_group = BuildingGroup.objects.get(id='id')
qs = building_group.buildings.all()
return qs