问题描述
我有一个模型与以下不同:
I have a model not unlike the following:
class Bike(models.Model):
made_at = models.ForeignKey(Factory)
added_on = models.DateField(auto_add_now=True)
用户可以在多个工厂工作,因此他们的用户配置文件都有一个 ManyToManyField
到 Factory
。
All users may work at a number of factories and therefore their user profiles all have a ManyToManyField
to Factory
.
现在我想为 Bike
构建一个 ModelForm
,但是我想要 made_at
列表仅由当前用户工作的工厂组成。这个想法是,用户应该能够添加他们组装的自行车,并输入自行车的工厂。
Now I want to construct a ModelForm
for Bike
but I want the made_at
list to consist of only factories at which the current user works. The idea is that users should be able to add bikes that they've assembled and enter which of the factories the bike was made at.
我该怎么做? / p>
How do I do that?
推荐答案
你的问题可能是一个。
S. Lott's answer there is the ticket to solve your problem.He answered:
因此,向字段的queryset属性提供QuerySet。取决于您的表单的构建方式。如果你建立一个明确的表单,你将有直接命名的字段。
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)
如果您使用默认的ModelForm对象, form.fields [rate]。queryset = ...
这是在视图中显式完成的。没有黑客。
This is done explicitly in the view. No hacking around.
这篇关于具有特定字段的自定义查询器的Django ModelForm实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!