gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:14:30 24 4
gpt4 key购买 nike

我想弄清楚如何按值过滤 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"
]
]

最佳答案

好吧,我发现我做错了什么。它在 View 中。我没有在 View 上声明 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 过滤器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com