Django-filter '__in' lookup

2020-03-15 02:24发布

I am using django-rest-framework with https://github.com/alex/django-filter/, but question is mostly about django-filter. I can't understand how to use filters with "__in" lookup.

For example i have model:

class Book(models.Model):
   name = models.CharField(max_length=100)

class BookView(viewsets.ReadOnlyModelViewSet):
   serializer_class = BookSerializer()
   model = Book
   filter_fields = ('id', 'name')

And i can't use url like this

/v1/books/?id__in=1,2,3

to find books with id 1, 2 or 3

标签: python django
9条回答
够拽才男人
2楼-- · 2020-03-15 02:40

The documentation for django-filter is sparse. You could try creating a custom filter and specifying the lookup type. It's rather convoluted:

class BookFilter(django_filters.FilterSet):
    id = django_filters.NumberFilter(name="id", lookup_type="in")

    class Meta:
        model = Book
        fields = ['id']

And then modify your view to use the filter class:

class BookView(viewsets.ReadOnlyModelViewSet):
    serializer_class = BookSerializer()
    model = Book
    filter_fields = ('id', 'name')
    filter_class = BookFilter

You'll then be able to lookup books via their ids (note "__in" not used):

/v1/books/?id=1,2,3
/v1/books/?id=1
查看更多
Emotional °昔
3楼-- · 2020-03-15 02:42

The django-filter provides BaseInFilter to be used in conjunction with other filter classes, such as NumberFilter, CharFilter. This class only validates that the incoming request is comma-separated.So if you're using the Web Browsable API, you can send request as /book/?id__in=1%2C3 where %2C is comma.

filters.py

import django_filters


class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
    pass


class BookFilter(django_filters.FilterSet):
    id__in = NumberInFilter(field_name="id", lookup_expr="in")

views.py

from rest_framework import viewsets
from django_filters import rest_framework as filters

from book.filters import BookFilter
from book.models import Book
from book.serializers import BookSerializer


class BookViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Book.objects.all()
    filter_backends = (filters.DjangoFilterBackend, )
    filterset_class = BookFilter
    serializer_class = BookSerializer
查看更多
来,给爷笑一个
4楼-- · 2020-03-15 02:44

The question is discussed in this issue: https://github.com/alex/django-filter/issues/137#issuecomment-77697870

The suggested solution would be to create a custom filter as follows:

from django_filters import Filter
from django_filters.fields import Lookup

from .models import Product

class ListFilter(Filter):
    def filter(self, qs, value):
        value_list = value.split(u',')
        return super(ListFilter, self).filter(qs, Lookup(value_list, 'in'))

class ProductFilterSet(django_filters.FilterSet):
    id = ListFilter(name='id')

    class Meta:
        model = Product
        fields = ['id']

And the you can write the following:

products/?id=7,8,9

查看更多
贪生不怕死
5楼-- · 2020-03-15 02:50

Instead /v1/books/?id__in=1,2,3 you can use /v1/books/?id=1&id=2&id=3

查看更多
成全新的幸福
6楼-- · 2020-03-15 02:53

I have just answered the same question in DjangoFilterBackend with multiple ids

For your case, this should work without having to write any logic.

from django_filters import rest_framework as filters

class NumberInFilter(filters.BaseInFilter, filters.NumberFilter):
    pass


class BookFilter(filters.FilterSet):
    id_in = NumberInFilter(field_name='id', lookup_expr='in')

    class Meta:
        model = Book
        fields = ['id_in', 'name']

class BookView(viewsets.ReadOnlyModelViewSet):
   serializer_class = BookSerializer()
   model = Book
   filter_class = BookFilter

Now you should be able to filter by a list of ids in your get parameters, such as /v1/books/?id__in=1,2,3

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-03-15 02:55

The django admin site only create urls under the template app_name/model_name/primary_key to edit an instance of the model. It doesn't provide the __in filtering through URLS.

You have to create a custom view:

def myview(request):
    # you can get parameters from request.GET or request.POST
    selected_books = None
    if request.method = "POST":
        ids = request.POST["ids"].split("_")
        selected_books = Book.objects.filter(id__in=ids)

    return render_to_response('mytemplate.html', { 'selected_books': selected_books }, context_instance = RequestContext(request) )

And in mytemplate.html:

{% for entry in selected_books %}
  ... {{ entry }} ...
{% endfor %}

In urls.py add an entry to this view.

Then try a GET request to your URL with the parameters ?ids=1_2_3

查看更多
登录 后发表回答