根据查询参数进行筛选

2022-02-21 00:00:00 python django django-rest-framework

问题描述

我使用睡觉框架创建了我的接口,现在正在尝试对其进行筛选。

我的models.py是这样的:

class Airline(models.Model):
    name = models.TextField()

class Workspace(models.Model):
    airline = models.ForeignKey(Airline)
    name = models.CharField(max_length=100)

class Passenger(models.Model):
    workspace = models.ForeignKey(Workspace)
    title = models.CharField(max_length=200)

我希望在我的JSON文件中查看";特定工作区&或";特定航空公司&等的所有乘客。

这是我的serializers.py

class AirlineSerializer(serializers.ModelSerializer):
    class Meta:
        model = Airline


class WorkspaceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workspace


class PassengerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Passenger

views.py

class AirlineList(generics.ListCreateAPIView):
    model = Airline
    serializer_class = AirlineSerializer


class AirlineDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Airline
    serializer_class = AirlineSerializer


class WorkspaceList(generics.ListCreateAPIView):
    model = Workspace
    serializer_class = WorkspaceSerializer


class WorkspaceDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Workspace
    serializer_class = WorkspaceSerializer


class PassengerList(generics.ListCreateAPIView):
    model = Passenger
    serializer_class = PassengerSerializer


class PassengerDetail(generics.RetrieveUpdateDestroyAPIView):
    model = Passenger
    serializer_class = PassengerSerializer

我想使用Filtering against query parameter,但我真的拿不到.


解决方案

代码如下:

class PassengerList(generics.ListCreateAPIView):
    model = Passenger
    serializer_class = PassengerSerializer

    # Show all of the PASSENGERS in particular WORKSPACE
    # or all of the PASSENGERS in particular AIRLINE
    def get_queryset(self):
        queryset = Passenger.objects.all()
        workspace = self.request.query_params.get('workspace')
        airline = self.request.query_params.get('airline')

        if workspace:
            queryset = queryset.filter(workspace_id=workspace)
        elif airline:
            queryset = queryset.filter(workspace__airline_id=airline)

        return queryset

相关文章