How to overwrite get method in generic RetrieveAPIView in django rest framework to filter the results

蹲街弑〆低调 提交于 2019-12-11 16:57:07

问题


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

来源:https://stackoverflow.com/questions/56558396/how-to-overwrite-get-method-in-generic-retrieveapiview-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!