django forms.ModelChoiceField 过滤queryset中的结果

form中设置

复制代码
class TotalMarkForm(forms.Form):
    crew_infos = forms.ModelChoiceField(
        queryset=models.Crew2Train.objects.all(),
    )
    closing_date = forms.DateField()

    train_marks = forms.ModelChoiceField(
        queryset=models.TrainMark.objects.all(),
        label='车次',
        widget=forms.Select(attrs={'class': 'form-control', })
    )


    total = forms.FloatField(
        label='日进款',
        initial=0.0,
        widget=forms.NumberInput(attrs={'class': 'form-control'})
    )
    plan = forms.FloatField(
        label='日计划',
        initial=0.0,
        widget=forms.NumberInput(attrs={'class': 'form-control'})
    )
复制代码

想过滤点crew_infos里,当日未出现的班组

view中

复制代码
    if date_inquery:
        crew_train_formset = formset_factory(myform.TotalMarkForm, extra=m_num)
        total_mark_form = myform.TotalMarkForm()
        在return到前端生成以前,对TotalMarkForm里的属性重新赋值,
        total_mark_form.fields['crew_infos'] = forms.ModelChoiceField(
            queryset=models.TotalMark.objects.filter(closing_date=date_inquery),
            initial='乘务组',
            label='乘务组',
            error_messages={
                'required': '不能为空'
            },
            widget=forms.Select(attrs={'class': 'form-control', }),
        )
        total_mark_form.fields['closing_date'] = forms.DateField(
            label='日期',
            initial=date_inquery,
            widget=forms.DateInput(
                attrs={
                    'type': 'date',
                    'class': 'form-control',
                }
            )
        )
        total_mark_form.fields['train_marks'] = forms.ModelChoiceField(
            queryset=models.TotalMark.objects.filter()
        )

        return render(request, 'total_mark_edit.html', locals())
复制代码

 

posted @   笑而不语心自闲  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示