Django-Filter 使用 lookup_choices 获得自定义结果

Django-Filter Use lookup_choices for custom results

我有一个字段 profit_loss_value_fees,在这个字段中,我希望用户有一个下拉选项来显示 Profit/Loss/Scratch.

的所有交易
Profit = Trade.profit_loss_value_fees > 0
Loss = Trade.profit_loss_value_fees < 0
Scratch = Trade.profit_loss_value_fees == 0 

我所做的是一个 result1,它可以工作,但我没有得到上面提到的一个很好的下拉菜单。这是两个空白字段,用户可以在其中输入 1 和 100,然后显示该范围内的所有交易。它有效,但不是所需的外观。

filters.py

class StatsPortfolioFilter(django_filters.FilterSet):

    # Drop down with 3 options (Win, Loss, Scratch) using the Trade Field: profit_loss_value_fees
    result1 = django_filters.RangeFilter(
        field_name='profit_loss_value_fees',
        label='result1',
        )

我尝试的是使用 LookupChoiceFilter 创建 3 个下拉选项并且有效。显然,问题是这些选项什么都不做。我怎样才能添加

filters.py

class StatsPortfolioFilter(django_filters.FilterSet):

    # I need something that gives the lookup_choices value
    # w = Trade.profit_loss_value_fees > 0
    # l = Trade.profit_loss_value_fees < 0
    # s = Trade.profit_loss_value_fees == 0

    # Drop down with 3 options (Win, Loss, Scratch) using the Trade Field: profit_loss_value_fees
    result = django_filters.LookupChoiceFilter(
        field_name='profit_loss_value_fees', # field_name focuses on field relatetion
        label='Result',
        # field_class=forms.DecimalField,
        lookup_choices=[
            ('w', 'Win'),
            ('l', 'Loss'),
            ('s', 'Scratch'),
        ]
    )

目前还没有错误消息,因为我不知道如何继续。

尝试自定义筛选字段和方法以获得正确的查询,如下所示

class StatsPortfolioFilter(django_filters.FilterSet):
   WIN_LOSS_CHOICES = (
            ('w', 'Win'),
            ('l', 'Loss'),
            ('s', 'Scratch'),
        )
   result = django_filters.ChoiceFilter(empty_label='---------', label="Result", 
       choices=WIN_LOSS_CHOICES, method="trade_win_loss")

   def trade_win_loss(self, queryset, name, value):
        if (value == 'w'):
            return queryset.filter(profit_loss_value_fees__gt=0)
        if (value == 'l'):
            return queryset.filter(profit_loss_value_fees__lt=0)
        if (value == 's'):
            return queryset.filter(profit_loss_value_fees= 0)

        return queryset