DjangoFilterBackend与多个ids [英] DjangoFilterBackend with multiple ids

查看:504
本文介绍了DjangoFilterBackend与多个ids的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 django-filter 过滤我的模型。如果我通过一个id过滤,则可以正常工作:

I want to filter my model with django-filter. It works fine if I filter by one id like:

http://localhost:8000/accommodations?accommodationType_id=1

但是我不知道如何通过多个id进行过滤。

But I don't know how I can filter by multiple ids like.

http://localhost:8000/accommodations?accommodationType_id=1,2

我的实际 ViewSet 如下所示:

class AccommodationViewSet(viewsets.ReadOnlyModelViewSet):
    """
        REST API endpoint for 'accommodation' resource
    """
    queryset = Accommodation.objects.all()
    serializer_class = AccommodationSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('accommodationType_id', 'name')

我希望有一个解决方案。

I hope there is an solution.

推荐答案

我发现以下解决我的问题:)

I found the following solution for my problem :)

https://gist.github.com/aBuder/654fb945f085b17358d8

from webapp.serializers import *
from rest_framework import viewsets
from rest_framework import filters
from django_filters import Filter, FilterSet


class ListFilter(Filter):
    def filter(self, qs, value):
        if not value:
            return qs

        self.lookup_type = 'in'
        values = value.split(',')
        return super(ListFilter, self).filter(qs, values)


class AccommodationFilter(FilterSet):
    ids = ListFilter(name='id')
    accommodationType_ids = ListFilter(name='accommodationType_id')

    class Meta:
        model = Accommodation
        fields = ['ids', 'accommodationType_ids']


class AccommodationViewSet(viewsets.ReadOnlyModelViewSet):
    """
        REST API endpoint for 'accommodation' resource
    """
    queryset = Accommodation.objects.all()
    serializer_class = AccommodationSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = AccommodationFilter

这篇关于DjangoFilterBackend与多个ids的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆