我有这个小科学怪人:
from dynamic_rest.viewsets import DynamicModelViewSet
class QuarterFilter(django_filters.Filter):
def get_quarter_range(self, quarter):
if quarter == 1:
return [1, 3]
elif quarter == 2:
return [4, 6]
elif quarter == 3:
return [7, 9]
elif quarter == 4:
return [10, 12]
else:
raise ValidationError("quarter value must be range from 1-4")
def filter(self, qs, value):
try:
year, quarter = value.split("Q")
year, quarter = int(year), int(quarter)
qs = qs.filter(date__year=year)
qs = qs.filter(date__month__range=self.get_quarter_range(quarter))
except:
pass
return qs
class OperationViewSet(DynamicModelViewSet):
queryset = Operation.objects.all()
serializer_class = OperationSerializer
permission_classes = (AllowAny,)
def get_queryset(self, *args, **kwargs):
# TODO: how to implement a .quarter operator at the Dynamic REST level?
queryset = Operation.objects.all()
quarter = self.request.query_params.pop('filter{date.quarter}')
if quarter:
queryset = QuarterFilter().filter(queryset, quarter[0])
return queryset
Dynamic Rest和Django Filter
的混合体。
它可以工作,但我不喜欢它,特别是因为如果在选择该过滤器所适用的字段时没有灵活性,那么它会被硬编码为date.quarter
。我不想通过重新发明轮子来扩展这个概念。相反,我想扩展由动态休息实现的强大机制。动态休息支持一堆operators。
将实现上述功能的操作员列表扩展为包括.quarter
运算符的公认方法是什么?