How do I filter ForeignKey choices in a Django ModelForm?

前端 未结 7 1933
感情败类
感情败类 2020-11-22 09:07

Say I have the following in my models.py:

class Company(models.Model):
   name = ...

class Rate(models.Model):
   company = models.ForeignKey(C         


        
7条回答
  •  鱼传尺愫
    2020-11-22 09:36

    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.

提交回复
热议问题