Django Rest Framework(多对多字段上的 GET 过滤器)

Posted

技术标签:

【中文标题】Django Rest Framework(多对多字段上的 GET 过滤器)【英文标题】:Django Rest Framework (GET filter on ManyToMany field) 【发布时间】:2014-11-14 14:38:00 【问题描述】:

我试图弄清楚如何按值过滤 ManyToMany 字段。在 Django 中,它就像 queryset.filter(m2mfield__name) 一样简单,但我无法弄清楚我缺少什么。我正在使用Django Rest Framework 和DjangoFilterBackend。

型号:

class City(models.Model):
    name = models.CharField(max_length=80)

class State(models.Model):
    name = models.CharField(max_length=50)
    cities = models.ManyToManyField(City)

过滤器:

import django_filters

class StateFilter(django_filters.FilterSet):
    cities = django_filters.CharFilter(
        name='cities__name',
        lookup_type='contains',
    )

    class Meta:
        model = State
        fields = ('name', 'cities')

序列化器:

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ('name', )

class StateSerializer(serializers.ModelSerializer):
    cities = CitySerializer(many=True)

    class Meta:
        model = State
        fields = ('name', 'cities')
        filter_class = StateFilter

查看:

from rest_framework.generics import ListAPIView, RetrieveAPIView
from .serializers import StateSerializer

class StateList(ListAPIView):
    queryset = State.objects.all()
    serializer_class = StateSerializer
    filter_fields = ('name', 'cities')

../api/states/ 的输出当前是:

 [
     "name": "Florida",
     "cities": [
          "name": "Tampa",
          "name": "St. Petersburg",
          "name": "Orlando"
     ],
     "name": "North Carolina",
     "cities": [
          "name": "Raleigh",
          "name": "Charlotte",
          "name": "Greensboro"
     ]
 ]

如何通过 GET 调用按名称过滤城市,例如:

../api/states/?cities=Charlotte

上面的结果应该是:

 [
     "name": "North Carolina",
     "cities": [
          "name": "Raleigh",
          "name": "Charlotte",
          "name": "Greensboro"
     ]
 ]

【问题讨论】:

你能展示你的 ViewSet 吗? @Zulu,我已按要求添加了 ViewSet。 REST_FRAMEWORK = 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend', 【参考方案1】:

好吧,我发现我做错了什么。它在视图中。我没有在视图上声明 filter_class:

from rest_framework.generics import ListAPIView, RetrieveAPIView
from .serializers import StateSerializer
from .filters import StateFilter

class StateList(ListAPIView):
    queryset = State.objects.all()
    serializer_class = StateSerializer
    filter_fields = ('name', 'cities')
    filter_class = StateFilter  # This was missing

我不小心把它放在了序列化器上。

【讨论】:

以上是关于Django Rest Framework(多对多字段上的 GET 过滤器)的主要内容,如果未能解决你的问题,请参考以下文章

如何在Django Rest Framework中序列化三个具有多对多关系的模型

如何在 Django REST 框架中为多对多字段定义“IsOwner”自定义权限?

如何使用 Django Rest Framework 向 ManyToMany 字段添加数据?

Django Rest Framework 中的嵌套序列化程序“通过模型”

如何使用 django rest 框架保存多对多字段对象

我需要显示与相同模型有多对多关系的相关字段。 Django Rest Frame工作