在Django rest框架中,有没有办法有多个查找字段?我知道这听起来对 REST 不是很友好。
我有一个 Company
模型,我想先通过他们的国家/地区列出它们,然后通过 slug 字段列出它们,例如:/companies/<iso_country>/<slug>/
.有办法做到这一点吗?
最佳答案
像这样创建mixin:
class MultipleFieldLookupMixin(object):
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
filter[field] = self.kwargs[field]
return get_object_or_404(queryset, **filter) # Lookup the object
并将此混合添加到您的 View 集中:
class YourCountryViewSet(MultipleFieldLookupMixin, generics.RetrieveAPIView):
lookup_fields = ('iso_country', 'slug')
...
来源:http://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins
关于python - 具有多个查找字段的 Rest 调用用于反向查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365906/