Python 在多对多关系上使用django MultipleChoiceField上的初始值
在我的模型中,我有:Python 在多对多关系上使用django MultipleChoiceField上的初始值,python,django,Python,Django,在我的模型中,我有: flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT) lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True) 在我的表格中,我希望这些是可选择的,基于可用的流线。因此,我将flowcell弹出到一个变量,并使用它查看
flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT)
lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True)
在我的表格中,我希望这些是可选择的,基于可用的流线。因此,我将flowcell弹出到一个变量,并使用它查看有哪些“车道”:
class DemuxerForm(forms.ModelForm):
class Meta:
model = Demuxer
exclude = ["owner", "pid", "flowcell"]
lanes = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
self.flowcell = kwargs.pop('flowcell')
super().__init__(*args, **kwargs)
self.fields['lanes'].choices = sorted([(lane.pk, str(lane.lane_number))
for lane in self.flowcell.lanes.all()])
现在我想勾选所有可用的复选框。但我不知道我怎么能做到。在initial=可能的位置,“self”不可用。。。有什么想法吗?我想出来了:
choices = self.flowcell.lanes.values_list("pk", lane_number").order_by("lane_number")
self.fields['lanes'].choices = choices
self.fields["lanes"].initial = [pk for pk, _ in choices]