我正在努力使用django rest framework和django-filters(http://django-filter.readthedocs.io/en/master/)来过滤出生日期的生日。
最大的问题是使用django常用过滤器我需要做类似
的事情class birthdayFilter(django_filters.rest_framework.FilterSet):
day = django_filters.RangeFilter(name="born_date__day")
month = django_filters.RangeFilter(name="born_date__month")
class Meta:
Model = User
fields = ['day','month']
如果用户选择这样的时间段,则会出现问题: 27/11至1/12
在这种情况下,我总是会收到一个空的服务器响应,因为默认情况下它会尝试获取大于27且小于1的日期,总是没有。
另一个问题是如果用户选择以下内容: 27/10至1/01或27/10至1/12
我认为解决方法是弄脏我的手并编写我自己的过滤器,但django过滤器的文档并不清楚如何做到这一点。
答案 0 :(得分:0)
刚刚做过,没有经过全面测试,但似乎没问题。我只是认为时间段将通过" dd / mm-dd / mm"
def BirthdayFilter(queryset,name,value):
if not value:
return queryset
#considering value will be : xx/xx-xx/xx
dateBegin,dateEnd = value.split('-') #first split the Date Range
dayBegin,monthBegin = dateBegin.split('/')
dayBegin = int(dayBegin)
monthBegin = int(monthBegin)
dayEnd,monthEnd = dateEnd.split('/')
dayEnd = int(dayEnd)
monthEnd = int(monthEnd)
result = []
if monthEnd-monthBegin == 0: #dates at the same month, ok easy
if dayBegin > dayEnd:#not allowed
return result
result = queryset.filter(data_nascimento__day__range = (dayBegin,dayEnd),data_nascimento__month = monthBegin)
elif abs(monthEnd - monthBegin) > 0: #crossing month
#first the edges
edgeStart = queryset.filter(data_nascimento__day__range = (dayBegin,31), data_nascimento__month = monthBegin)
edgeEnd = queryset.filter(data_nascimento__day__range = (1,dayEnd), data_nascimento__month = monthEnd )
result = edgeStart | edgeEnd
if abs(monthEnd - monthBegin) > 1: #if it is bigger than 1, we have to add
#months in between
monthsInBetween = []
if monthBegin > monthEnd: #calendar crossing years
monthsInBetween = queryset.filter(data_nascimento__month__range = (monthBegin,12)) + Clientes.objects.filter(data_nascimento__month__range = (1,monthEnd))
else:
monthsInBetween = queryset.filter(data_nascimento__month__range = (monthBegin,monthEnd))
result = result | monthsInBetween
class UserFilter(django_filters.rest_framework.FilterSet):
birthday = django_filters.CharFilter(method = BirthdayFilter)
class Meta:
Model = User
fields = ['birthday']