How to overwrite get method in generic RetrieveAPI

2019-08-23 05:04发布

I have an API that can list several buildings. Each building belongs to several building groups and each building group contains several buildings.

I want to show single fields of one building group. More specifically I want to show all buildings of one building group in my RetrieveAPIView.

I can list a single BuildingGroup instance using the generic view like so:

class BuildingGroupRetrieveAPIView(RetrieveAPIView):
    serializer_class = BuildingGroupSerializer
    queryset = BuildingGroup.buildings.all()

I assume that I can overwrite the get method to only display a single field of that retrieved object. Specifically I want to display all the objects that are in my many to many relation. Or better to say, I want to retrieve all the complete data within my m2m relation.

Here are my models:

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)

I tried this without success:

 def get(self):
        building_group = BuildingGroup.objects.get(id='id')
        qs = building_group.buildings.all()
        return qs

my serializer

class BuildingGroupSerializer(serializers.ModelSerializer):

    class Meta:

        model = BuildingGroup

        fields = (
            'description',
             .....
        )

I can attach a screenshot to be more clear.

Any help is highly appreciated. Thanks in advance

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

enter image description here

0条回答
登录 后发表回答