Django编辑表单查询集的查询+当前选中的选项如何获取?

2024-04-25 13:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的表单.py在

class CreateVesselForm(forms.ModelForm):
class Meta:
    model = Vessel
    exclude = ['active']

# Filtering Choices
def __init__(self, *args, **kwargs):
    super(CreateVesselForm, self).__init__(*args, **kwargs)
    # Filtering just Free Slots
    self.fields['slot'].queryset = Slot.objects.filter(is_free=True)
    # Filtering just Free Storages
    self.fields['storage'].queryset = Storage.objects.filter(is_free=True)

Slot字段是ForeignKey,而Storage字段是manytomy字段。在

在我的视图.py,当我保存此表单时,我将“is_free”的状态更改为False。但是,当编辑此项(容器)时(从表单实例获取它)之前已经选择的选项不再出现在表单字段中,因为我的查询集只是按status=True进行筛选。在

对我来说,最完美的形式是:

对于ForeignKey

当前所选项目“容器.槽" + 插槽对象.filter(是否免费=真的)?在

多次

当前所选项目“容器.储存" + 存储.objects.filter(是否免费=真的)?在

有没有办法完成它?在


Tags: pyselftruefree表单objectsinitis
1条回答
网友
1楼 · 发布于 2024-04-25 13:46:02

你可以这样做:

class CreateVesselForm(forms.ModelForm):

    class Meta:
        model = Vessel
        exclude = ['active']

    # Filtering Choices
    def __init__(self, *args, **kwargs):
        super(CreateVesselForm, self).__init__(*args, **kwargs)
        if kwargs['instance']:
            self.fields['storage'].queryset = kwargs['instance'].storage.all()|Storage.objects.filter(is_free=True)
            self.fields['slot'].queryset = Slot.objects.filter(pk=kwargs['instance'].slot.pk)|Slot.objects.filter(is_free=True)

相关问题 更多 >