我想要合并两个模型:城市和国家/地区,以便拥有这样的过滤器:http://localhost:8000/api/v1/geo/location-search/?name=Santa+Fe
我有一个ModelViewSet,它返回如下的序列化数据:
class LocationSearchAPI(ModelViewSet):
queryset = City.objects.all().order_by('name')
permission_classes = [AllowAny]
serializer_class = CityListSerializer
filter_backends = (DjangoFilterBackend, SearchFilter)
filter_class = LocationFilter
def get_location_list(self, request):
city_qs = City.objects.all().order_by('name')
country_qs = Country.objects.all().order_by('name')
result_qs = list(chain(country_qs, city_qs))
sorted_list = sorted(result_qs, key=lambda instance: -instance.id)
results = list()
for item in sorted_list:
item_type = item.__class__.__name__.lower()
if isinstance(item, City):
serializer = CityLocaliaztionSrl(item)
if isinstance(item, Country):
serializer = CountryLocaliaztionSrl(item)
results.append({'type': item_type, 'data': serializer.data})
return Response(results, status=200)
并且此过滤器不起作用:
class LocationFilter(FilterSet):
class Meta:
model = City
fields = ('type', 'data__name')
如何在ModelViewSet中使用Django Filters返回序列化数据,希望你们帮助我。