在带有django-rest-framework的过滤器中使用自定义方法 [英] Using custom methods in filter with django-rest-framework
问题描述
我想根据我的REST API中的查询参数进行过滤-参阅django文档。
但是,我要过滤的一个参数只能通过模型@property
I would like to filter against query params in my REST API - see django docs on this. However, one parameter I wish to filter by is only available via a model @property
example models.py:
example models.py:
class Listing(models.Model):
product = models.OneToOneField(Product, related_name='listing')
...
@property
def category(self):
return self.product.assets[0].category.name
这是我的Listing API的设置,符合 django-filter文档
Here is the setup for my Listing API in accordance with django-filter docs
class ListingFilter(django_filters.FilterSet):
product = django_filters.CharFilter(name='product__name')
category = django_filters.CharFilter(name='category') #DOES NOT WORK!!
class Meta:
model = Listing
fields = ['product','category']
class ListingList(generics.ListCreateAPIView):
queryset = Listing.objects.all()
serializer_class = ListingSerializer
filter_class = ListingFilter
如何适当地通过listing.category进行过滤?
How can I appropriately filter by listing.category? It is not available on the listing model directly.
推荐答案
使用'action'参数指定自定义方法-请参阅django-filter文档
Use the 'action' parameter to specify a custom method - see django-filter docs
首先定义一个使用category参数值过滤查询集的方法:
First define a method that filters a queryset using the value of the category parameter:
def filter_category(queryset, value):
if not value:
return queryset
queryset = ...custom filtering on queryset using 'value'...
return queryset
列表过滤器应如下所示:
Listing filter should look like this:
class ListingFilter(django_filters.FilterSet):
...
category = django_filters.CharFilter(action=filter_category)
...
这篇关于在带有django-rest-framework的过滤器中使用自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!