如何通过Django过滤器中的用户输入过滤数据框?

时间:2019-04-09 07:05:25

标签: python django django-forms django-filter django-pandas

我要过滤从模型中透视的数据框。

Model.py是:

class MTD(models.Model):
    RGN = models.CharField(max_length = 60, db_column = 'RGN')
    Channel = models.CharField(max_length = 60, db_column = 'Channel')
    Vertical = models.CharField(max_length = 60, db_column = 'Vertical')
    Brand = models.CharField(max_length = 60, db_column = 'Brand')
    Sales_Value = models.CharField(max_length = 60, db_column = 'Sales Value')
    Month = models.CharField(max_length = 60, db_column = 'Month')

    City = models.CharField(max_length = 60, db_column = 'City')

    objects = models.Manager()
    pdobjects = DataFrameManager()


    def __str__(self):
            field_values = []
            for field in self._meta.get_fields():
                field_values.append(str(getattr(self, field.name, '')))
            return ' '.join(field_values)

我仅从模型中过滤三列(“垂直”,“频道”,“销售值”),并将其转换为数据框。从导出的数据帧中,我无法按照用户的要求过滤数据。我正在发布到目前为止已经尝试过的代码。

Table.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    {% load static %}
    <meta charset="utf-8">
    <title></title>
  </head>
  <body class="hold-transition skin-blue sidebar-mini">
    <h1>Pandas dataframe from MyModel</h1>
    <form method="GET">
      {{ filter.form.as_p }}
      <button type="submit">Search</button>
    </form>

    {{ filter|safe }}
    {{ Table|safe }}

  </body>
</html>

Filter.py

from dash.models import MTD
import django_filters

class UserFilter(django_filters.FilterSet):
    class Meta:
        model = MTD
        fields = ['Vertical', 'Channel', ]

Views.py

from dash.filter import UserFilter


def salebycustomer(request):
    sbc = MTD.pdobjects.values('Vertical', 'Channel','Sales_Value')
    user_filter = UserFilter(request.GET, queryset=sbc)
    sbc_df = sbc.to_dataframe().reset_index(drop=True)#Trying to use filtered model for dataframe
    sbc_df['Sales_Value']=sbc_df['Sales_Value'].astype(float)

    sbc_df1 = pandas.pivot_table(sbc_df,values='Sales_Value', index='Vertical', columns='Channel',aggfunc='sum').rename_axis(None,axis=1).replace(numpy.nan,0)
    sbc_df1.reset_index(inplace=True)

    # sbc_df1.columns = [''.join(col).strip() for col in sbc_df1.columns.values]

    # sbc_df1=sbc_df1.T.to_dict().values()
    template = 'table.html'


    sbc_df2 = sbc_df1.to_html()

    context= {'filter': user_filter,'Table':sbc_df2}

    return render(request, template, context)

请帮助我解决此问题。 Kindly refer this screenshot

谢谢

1 个答案:

答案 0 :(得分:0)

您知道吗,在创建user_filter时,您不会使用它在模板中创建输出或在视图中实际过滤某些内容。请特别注意django_filter文档的this section。过滤器也用于生成输出(不仅是表单)。