Django ModelForm instance with custom queryset for a specific field

喜夏-厌秋 提交于 2019-11-30 03:01:57
cethegeek

You question might be a dupe of this.

S. Lott's answer there is the ticket to solve your problem. He answered:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

try something like this in the view

form  = BikeForm()
form.fields["made_at"].queryset = Factory.objects.filter(user__factory)

modify the Factory queryset so that it identifies the factory which the user works at.

Nowaday, you should use:

    form.base_fields['alumno_item'].queryset = AlumnoItem.objects.prefetch_related(
        'alumno',
        'alumno__estudiante',
        'alumno__estudiante__profile',
        'item'
    )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!