0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Django REST framework] 対象フィールドをOR条件で複数検索したい。

Posted at

下記リクエストで3件の結果を得たい。
GET /api/v1/incident/?id=1,2,3

models.py
from django.db import models

class Auther(models.Model):
    author_name = models.CharField()

class Book(models.Model):

    book_name = models.CharField()
    book_author = models.ForeignKey(Auther)
serializers.py
from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):

    class Meta:
        model = Book
        fields = '__all__'
views.py
from rest_framework import viewsets

class BookViewSet(viewsets.ModelViewSet):

    queryset = Book.objects.all()
    serializer_class = serializers.BookSerializer
    filterset_class = filters.BookFilter
filters.py
from django.db.models import Q
from django_filters import rest_framework as filters

class MultiValueFilter(filters.Filter):

    def __init__(self, *args, **kwargs):
        self.lookup_expr = kwargs.pop('lookup_expr')
        super(MultiValueFilter, self).__init__(*args, **kwargs)

    def filter(self, queryset, value):
        q = Q()
        url_args = value.split(',') if value else []

        for arg in url_args:
            q = q | Q(**{self.lookup_expr: arg})
        return queryset.filter(q)

class BookFilterFilter(filters.FilterSet):

    id = MultiValueFilter(lookup_expr='id__exact')

    class Meta:
        model = models.Book
        fields = '__all__'

検索条件 説明
exact 完全一致
iexact 大文字小文字を区別しない完全一致
contains 指定の値を含む
icontains 大文字小文字を区別しない指定の値を含む
startswith 指定の値で始まる
istartswith 大文字小文字を区別しない指定の値で始まる
endswith 指定の値で終わる
iendswith 大文字小文字を区別しない指定の値で終わる
gt 指定の値より大きい
gte 指定の値以上
lt 指定の値より小さい
lte 指定の値以下
in 与えられたリストまたはタプルのいずれかの値と一致
range 指定の範囲内の値と一致
year 日付フィールドの年と一致
month 日付フィールドの月と一致
day 日付フィールドの日と一致
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?