Django筛选器软件包:如何筛选对象以创建统计信息而非列表 [英] Django-Filter Package: How To Filter Objects To Create Stats And Not Lists

查看:58
本文介绍了Django筛选器软件包:如何筛选对象以创建统计信息而非列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django-Filter 软件包,该软件包对他们的文档中有一个示例.但是,我并不是试图生成对象列表,而是过滤对对象字段所做的计算.

I'm using Django-Filter package which is working well for the one example they have in their documentation. However, I am not trying to generate a list of objects rather filter the calculations I have done on the object fields.

示例模板: https://django-filter.readthedocs.io/en/stable/guide/usage.html#the-template

{% for obj in filter.qs %}
    {{ obj.name }} - ${{ obj.price }}<br />
{% endfor %}

这里的问题是创建了一个列表..我正在寻找要根据新过滤器选择进行更新的交易统计".

The problem here is that a list is created.. I'm looking for my trade "stats" to be updated based on the new filter selections.

我认为我需要以不同的方式设置我的视图,并可能以另一种方式调用模板对象,但不能完全确定.

I believe I need to set up my views differently and possibly call the template objects in another way as well but not totally sure.

filters.py

filters.py

class StatsFilter(django_filters.FilterSet):  
    class Meta:
        model = Trade
        fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']

views.py

class StatsView(LoginRequiredMixin, FilterView):
    model = Trade
    template_name = 'dashboard/stats.html'
    filterset_class = StatsFilter

    def get_form(self, *args, **kwargs):
        form = StatsFilter()
        user = self.request.user
        form.fields['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
        return form

    def get_context_data(self, *args, **kwargs):
        trade = Trade.objects.filter(user=self.request.user, status='cl').order_by('created')
        all_trades = Trade.objects.filter(user=self.request.user, status='cl').count()
        context = super(StatsView, self).get_context_data(*args, **kwargs)
        data = [t.profit_loss_value_fees for t in trade]

        context['all_trades'] = all_trades
        context['gross_profit'] = sum([t.profit_loss_value for t in trade])
        context['net_profit'] = sum([t.profit_loss_value_fees for t in trade])
        ...
        return context    

stats.html

stats.html

            <form method="get" class="row">
                {{ filter.form.as_p }}
                {{ form.media }}

                <div class="col-xl-12">
                    <button class="btn btn-success float-right" type="submit">Apply</button>
                </div>
            </form>

            <table class="table table-striped">
                <tr>
                    <th scope="row">Net Profit <small>(Fees Included)</small></th>
                    <td>
                        {% if net_profit >= 0 %}
                        <font color="green">{{ net_profit|floatformat:2 }}</font>
                        {% else %}
                        <font color="red">{{ net_profit|floatformat:2 }}</font>
                        {% endif %}
                    </td>
                </tr>

                <tr>
                    <th scope="row">Gross Profit</th>
                    <td>{{ gross_profit|floatformat:2 }}</td>
                </tr>

推荐答案

花了我数周时间才发现的秘密秘诀是如此明显.在过滤器上运行计算.下面的例子.另外,您不需要使用聚合.与我上面写的原始方式一样好.

The secret sauce that took me weeks to find out is so obvious. Run the calcs over the filter. Example below. Also you do not need to use aggregate. Works just as well with the original way I wrote above.

context['gross_profit'] = sum([t.profit_loss_value for t in trade])

这是关键部分:

trades = filter.qs.filter(status='cl')

view.py

def get_context_data(self, *args, **kwargs):
    filter = StatsFilter(self.request.GET, queryset=self.get_queryset(), request=self.request)
    trades_count = filter.qs.filter(status='cl').count()
    trades = filter.qs.filter(status='cl')
    ...
    context['gross_profit'] = trades.aggregate(value=Sum('profit_loss_value'))['value']

这篇关于Django筛选器软件包:如何筛选对象以创建统计信息而非列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆