【问题标题】:Django-Filter Use lookup_choices for custom resultsDjango-Filter 使用lookup_choices 获取自定义结果
【发布时间】:2021-10-01 20:38:07
【问题描述】:

我有一个字段profit_loss_value_fees,我希望用户在这个字段中有一个下拉选项来显示所有盈利/亏损/临时交易。

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'),
        ]
    )

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

【问题讨论】:

    标签: django filter django-forms django-filter


    【解决方案1】:

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

    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
    

    【讨论】:

    • 这绝对是一种魅力,谢谢!
    猜你喜欢
    • 2013-02-20
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多