gpt4 book ai didi

python - 过滤外键日期 django_filters

转载 作者:行者123 更新时间:2023-11-28 17:55:58 26 4
gpt4 key购买 nike

目前我的过滤器可以正常工作,所以我可以根据名称进行过滤。但是我也想过滤发布(因此显示发布日期在一定范围内的游戏)

我该怎么做?

过滤器.py

class ReleaseFilter(django_filters.FilterSet):

date = django_filters.DateFromToRangeFilter(field_name='date')

class Meta:
model = Release
fields = ['date']

class GameFilter(django_filters.FilterSet):

name = django_filters.CharFilter(lookup_expr='icontains')
releases = ReleaseFilter()

class Meta:
model = Game
fields = ['releases']

模型.py

class Game(models.Model):
name = models.CharField(max_length=255)


class Release(models.Model):
game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE)
date = models.DateField()

最佳答案

您可以做的是使用 distinct=True 定义过滤字段:

This option can be used to eliminate duplicate results when using filters that span relationships.

例子:

release_date = django_filters.DateFromToRangeFilter(field_name='releases__date', distinct=True)

关于 Repl.it 的完整工作示例.查询结果示例:https://drf-filters-distinct--frankie567.repl.co/games/?release_date_after=2019-01-01&release_date_before=2019-12-31

关于python - 过滤外键日期 django_filters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58412856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com