在 Django 的 inlineformset_factory 中选择外键元素的子集
我有一个带有两个外键的模型:
class Model1(models.Model):
model_a = models.ForeignKey(ModelA)
model_b = models.ForeignKey(ModelB)
value = models.IntegerField()
然后,我创建一个内联表单集类,如下所示:
an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a")
然后实例化它,如下所示:
a_formset = an_inline_formset(request.POST, instance=model_A_object)
一旦此表单集在模板/页面中呈现,就会有与 model_b 字段关联的 ChoiceField。我遇到的问题是生成的下拉菜单中的元素包含 ModelB 表中找到的所有元素。我需要根据 ModelB 中的某些标准选择其中的一个子集。同时,在实例化 inlineformset_factory 时,我需要保留对 model_A_object 实例的引用,因此,我不能只使用 这个示例。有什么建议吗?
I have a model with two foreign keys:
class Model1(models.Model):
model_a = models.ForeignKey(ModelA)
model_b = models.ForeignKey(ModelB)
value = models.IntegerField()
Then, I create an inline formset class, like so:
an_inline_formset = inlineformset_factory(ModelA, Model1, fk_name="model_a")
and then instantiate it, like so:
a_formset = an_inline_formset(request.POST, instance=model_A_object)
Once this formset gets rendered in a template/page, there is ChoiceField associated with the model_b field. The problem I'm having is that the elements in the resulting drop down menu include all of the elements found in ModelB table. I need to select a subset of those based on some criteria from ModelB. At the same time, I need to keep the reference to the instance of model_A_object when instantiating inlineformset_factory and, therefore, I can't just use this example. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要做的是 更改 ModelChoiceField 的查询集
最简单的方法可能是对表单集的表单进行猴子修补。您应该能够在构建表单集后立即执行此操作:
不是最漂亮的,但它应该可以工作。
What you need to do is change the ModelChoiceField's queryset
The easiest way to do this may be to monkey-patch the formset's form. You should be able to do this right after constructing the formset with:
Not the prettiest, but it should work.