我试图弄清楚如何按值过滤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 /州/?城市=夏洛特
上述结果应为:
[
"name": "North Carolina",
"cities": [
"name": "Raleigh",
"name": "Charlotte",
"name": "Greensboro"
]
]
答案 0 :(得分:6)
好吧,我发现了我做错了什么。它在视野中。我没有在视图上声明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
我不小心把它放在了序列化器上。