我有一个与以下类似的模型:
class Bike(models.Model):
made_at = models.ForeignKey(Factory)
added_on = models.DateField(auto_add_now=True)
所有用户可能在多个工厂工作,因此他们的用户文件都有一个
ManyToManyField
至 Factory
.现在我想构建一个
ModelForm
为 Bike
但我想要 made_at
列表仅包含当前用户工作的工厂。这个想法是,用户应该能够添加他们已经组装的自行车,并进入制造自行车的工厂。我怎么做?
最佳答案
您的问题可能是 dupe of this .
S. Lott的 answer有一张票可以解决您的问题。
他回答:
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.
关于具有特定字段的自定义查询集的 Django ModelForm 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1821289/