如何在Django中使用查询字符串来过滤查询集?

44u64gxh  于 2023-06-25  发布在  Go
关注(0)|答案(4)|浏览(166)

我使用REST框架创建了我的“API”,现在我正在尝试为它做过滤。
下面是我的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

我想使用过滤对查询参数,但我不能真正得到它...

tzxcd3kk

tzxcd3kk1#

下面是代码:

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
jxct1oxe

jxct1oxe2#

你可以通过使用django-filter包来获得相同的功能,如文档中所述:DjangoFilterBackend

from rest_framework import filters 

class PassengerList(generics.ListCreateAPIView):
    model = Passenger
    serializer_class = PassengerSerializer
    queryset = Passenger.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('workspace', 'workspace__airline')

在这种情况下,您必须使用workspace=1workspace__airline=1进行过滤。

lskq00tm

lskq00tm3#

这个django app使用传入的查询参数在视图的查询集上应用过滤器,这种方式简洁而优雅。
可以使用pip安装为pip install drf-url-filters

使用示例

  • 验证.py*
from filters.schema import base_query_param_schema
from filters.validations import (
    CSVofIntegers,
    IntegerLike,
    DatetimeWithTZ
)

# make a validation schema for players filter query params
players_query_schema = base_query_param_schema.extend(
    {
        "id": IntegerLike(),
        "name": unicode,
        "team_id": CSVofIntegers(),  # /?team_id=1,2,3
        "install_ts": DatetimeWithTZ(),
        "update_ts": DatetimeWithTZ(),
    }
)
  • views.py*
from rest_framework import (
    viewsets,
    filters,
)

from .models import Player, Team
from .serializers import PlayerSerializer, TeamSerializer
from .pagination import ResultSetPagination
from .validations import teams_query_schema, players_query_schema
from filters.mixins import (
    FiltersMixin,
)

class PlayersViewSet(FiltersMixin, viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """
    serializer_class = PlayerSerializer
    pagination_class = ResultSetPagination
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('id', 'name', 'update_ts')
    ordering = ('id',)

    # add a mapping of query_params to db_columns(queries)
    filter_mappings = {
        'id': 'id',
        'name': 'name__icontains',
        'team_id': 'teams',   # many-to-many relationship
        'install_ts': 'install_ts',
        'update_ts': 'update_ts',
        'update_ts__gte': 'update_ts__gte',
        'update_ts__lte': 'update_ts__lte',
    }

    # add validation on filters
    filter_validation_schema = players_query_schema

    def get_queryset(self):
        """
        Optionally restricts the queryset by filtering against
        query parameters in the URL.
        """
        query_params = self.request.query_params
        queryset = Player.objects.prefetch_related(
            'teams'  # use prefetch_related to minimize db hits.
        ).all()

        # This dict will hold filter kwargs to pass in to Django ORM calls.
        db_filters = {}

        # update filters dict with incoming query params and then pass as
        # **kwargs to queryset.filter()
         db_filters.update(
            self.get_queryset_filters(
                query_params
            )
        )
        return queryset.filter(**db_filters)
5fjcxozz

5fjcxozz4#

你可以使用查询字符串来过滤Django中的查询集。您可以使用传入的查询参数对视图的查询集应用筛选器。
下面是一个如何过滤查询集的示例:

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

    def get_queryset(self):
        queryset = Passenger.objects.all()
        workspace_id = self.request.query_params.get('workspace_id', None)
        airline_id = self.request.query_params.get('airline_id', None)
        if workspace_id is not None:
            queryset = queryset.filter(workspace_id=workspace_id)
        if airline_id is not None:
            queryset = queryset.filter(workspace__airline_id=airline_id)
        return queryset

在这个例子中,你可以通过workspace_id和airline_id来过滤你的查询集。如果workspace_id不为None,则它将按workspace_id过滤查询集。如果airline_id不为None,则按workspace__airline_id3过滤查询集。

相关问题