【问题标题】:Django :How can I let my modelChoiceField take two possible types of modelsDjango:如何让我的 modelChoiceField 采用两种可能的模型
【发布时间】:2018-09-20 05:59:25
【问题描述】:
我需要让 modelChoiceField 有可能采用两个不同的模型对象。
例如 billnum 可以同时作为查询集:facture_ventes.objects 或 facture_depc.objects 而不是只有一个模型:
billnum=forms.ModelChoiceField(queryset=facture_ventes.objects)
感谢您的帮助
【问题讨论】:
标签:
django
forms
django-models
modelchoicefield
【解决方案1】:
我假设模型具有相同的字段。您可能想要重新设计您的项目,以便您拥有一个模型,并且该模型上可能还有一个额外的字段来区分ventes 和depc。这是我的建议。
否则,您也许可以使用union 查询。
billnum = forms.ModelChoiceField(
queryset=facture_ventes.objects.union(facture_depc.objects.all())
)
即便如此,您还是必须能够区分facture_ventes 和facture_depc 的pks。它太复杂了。改变你的模型。