python - 通过我的 Django 模型访问选择

标签 python django

设置.py
PERIODS = (
    ('day', _('Per day')),
    ('week', _('Per week')),
    ('month', _('Per month')),
    ('year', _('Per year')), 
) 

模型.py
class Statistics(TimeStampedModel):

    @property
    def per_period(self):
        return settings.PERIODS[self.] 

    def nb_of_customers_per_period(self):
        pass

View .py
class StatisticsIndexView(StaffRestrictedMixin, TemplateView):
    model = Statistics()
    template_name = 'loanwolf/statistics/index.html'

    def get_context_data(self, **kwargs):
        context = super(StatisticsIndexView, self).get_context_data(**kwargs)
        context.update({
            'applications_by_state': ApplicationsByState(),
            'applications_calendar': ApplicationsCalendar(),
            'new_customers_calendar': NewCustomersCalendar(),
            'statistics': Statistics(),
            'form': StatisticsBaseForm(),
        })
        return context

表单.py
class StatisticsBaseForm(forms.Form):
    type_choice = forms.ChoiceField(label=_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, initial=0, required=False)
    period = forms.ChoiceField(label="Period", choices=settings.PERIODS, initial='week', required=False)
    from_regular_product = forms.ModelChoiceField(
        queryset=ProductConfig.objects.filter(pk=-1), required=False,
        label=_('Product'))
    from_special_product = forms.ModelChoiceField(
        queryset=ProductConfig.objects.filter(pk=-1), required=False,
        label=_('Product'))
    product_type = forms.ChoiceField(
        choices=settings.LOANWOLF_PRODUCT_TYPE_CHOICES, required=False,
        initial='regular', label=_('Product type'))
    debit_frequency = forms.ChoiceField(
        choices=settings.LOANWOLF_PRODUCT_DEBIT_FREQUENCIES_CHOICES,
        required=False)

    def __init__(self, *args, **kwargs):
        super(StatisticsBaseForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_class = 'row'
        self.helper.layout = StatisticalToolsLayout

        company = get_current_company()
        regular_products = company.available_products.filter(
            is_active=True, product_type='regular')
        special_products = company.available_products.filter(
            is_active=True, product_type='special')

        self.fields['from_regular_product'].queryset = regular_products
        self.fields['from_special_product'].queryset = special_products

        if regular_products:
            self.fields['from_regular_product'].initial = \
                settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX

        if special_products:
            self.fields['from_special_product'].initial = \
                settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX

    class Meta:
        model = Statistics
        fields = '__all__'

好的,这是我的问题。我有一个 form使用 period 下拉菜单,我可以选择不同类型的周期(Per dayPer weekPer month每年)。例如,如果我选择 Per week,我想通过带有 self.something 的 Statistics 模型访问这个选项。提前抱歉,但我是 Django/Python 的新程序员。我怎么能做这样的事?我是否需要使用 form 中的 Apply 按钮发送内容? ?

更新

在我的 django 项目中,可以使用 CustomerProfile.objects.all() 显示应用程序中的每个客户,并使用

查找特定客户的创建日期
In [12]: cust = CustomerProfile.objects.get(pk=100)

In [13]: cust.user.date_joined
Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548)

In [14]: cust
Out[14]: <CustomerProfile: FistName LastName's customer profile>

我想根据创建日期列出每天、每周、每月或每年创建了多少客户。结果的一个例子可能是

...
week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers
...

我可能需要一个开始日期和结束日期的范围,我们将在其中列出此类信息。 start_date 将是创建第一个客户的日期,创建的第一周将是第一个日期的那一周。很明显,end_date 是今天,最后一周就是这个 end_date 的那一周。

例如,如果我在下拉菜单中选择 Per week 并在表单中按 Apply,我想将信息发送到我的模型,这样我就可以编码我解释的内容。

最佳答案

嗯,我想你可以在你的表单中添加一个 save() 方法:

class StatisticsBaseForm(forms.Form):
    ... # the rest of the code
    def save(self):
        period = self.cleaned_data['period']
        # do something with the period
        get_user_create_by_period(period)

然后像这样在您的 View 中添加此表单:

class StatisticsIndexView(StaffRestrictedMixin, TemplateView):
    model = Statistics
    template_name = 'loanwolf/statistics/index.html'
    form_class = StatisticsBaseForm

当 View 检查所有提交的数据是否正确时,将调用表单的保存方法。在那里,在表单的 save() 方法中,您可以访问提交的数据,例如 self.cleaned_data['period']

我什至认为统计模型在这里毫无用处。

关于python - 通过我的 Django 模型访问选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46331744/

相关文章:

python - 是否有更短的方法或 pythonic 方法来生成遵循使用 BeautifulSoup 模式的自定义 html?

python - 优化变点测试循环

python - 将numpy结构化数组子集转换为numpy数组而不进行复制

python - 如果值有两个以上空格,Pandas 会替换 df 中的行值

python - BigQuery 类型错误 : to_pandas() got an unexpected keyword argument 'timestamp_as_object'

django - 使用模型的 __unicode__ 作为管理表单中的搜索字段

python - 根据相关表中的另一个字段注释该表中的字段

django - 如何在 django 1.9 之后使用 modelform 创建禁用字段

python - redis 使用 hget 命令存储 json 数据。同时获取强制获取所有 json 数据代替单个 json 变量

javascript - Django - 我已将 onclick 函数添加到 html 中,每当我单击不同的按钮时,它都会呈现相同的数据。如何解决这个问题?