我有两个简单关系的模型如下:
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
class PersonSession(models.Model):
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(null=True,
blank=True)
person = models.ForeignKey(Person, related_name='person_sessions')
class PersonFilter(django_filters.FilterSet):
start_time = django_filters.DateFromToRangeFilter(
name='person_sessions__start_time',
distinct=True
)
class Meta:
model = Person
fields = ('first_name', 'last_name', 'start_time')
class PersonList(generics.ListCreateAPIView):
queryset = Person.objects.all()
serializer_class = PersonSerializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend)
filter_class = PersonFilter
如图所示,我想使用DateFromToRangeFilter,我希望我能得到这样的api:
api/persons?start_time_before=2018-04-20&start_time_after=2018-04-18
但这根本不起作用。看起来像post中所述,这种类型的过滤器的实现存在错误,但是帖子中的解决方案对我来说不起作用,因为我会得到两个内连接并得到与我预期的完全不同的结果。 / p>
答案 0 :(得分:0)
class PersonFilter(django_filters.FilterSet):
start_time_before = DateFilter(name='person_sessions__start_time',lookup_expr=('gt'),)
start_time_after = DateFilter(name='person_sessions__start_time',lookup_expr=('lt'))
如果你想要相同的网址,你可以使用这个类。
答案 1 :(得分:0)
我也有类似的情况。也许对某人会有所帮助。
class Task(ComputedFieldsModel):
created_at = models.DateTimeField(auto_now_add=True)
tco_at = models.DateTimeField(null=True, blank=True)
class TaskRangeStatisticsView(GenericAPIView):
queryset = Task.objects.all()
serializer_class = TaskRangeStatisticsSerializer
filterset_class = TaskRangeStatisticsBackend
def get(self,request):
queryset = self.filter_queryset(self.get_queryset()) \
.annotate(date=TruncDay('created_at')) \
.values("date") \
.annotate(finished_count=Count('tco_at'),created_count=Count('created_at'),in_progress_count=Count('in_progress_at')) \
.order_by("-date")
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
class TaskRangeStatisticsBackend(df_filters.FilterSet):
date = df_filters.DateFromToRangeFilter(field_name="created_at")
# 'date_after': '2016-01-01', 'date_before': '2016-02-01'
class Meta:
model = Task
fields = ["date"]
现在像http://127.0.0.1:8000/api/v1/test_tasks_statistics/?date_after=2021-06-01&date_before=2021-06-04
这样的查询工作正常