Django Edit Form Queryset 由 Query + Current Selected Option 组成 - 如何获取?

Django Edit Form Queryset made of Query + Current Selected Option - How to get?

我的forms.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)

槽字段是外键,存储字段是多对多字段。

在我的 views.py 中,当我保存此表单时,我将 "is_free" 的状态更改为 False。然而,当编辑这个项目(Vessel)的时候 - 从表单实例中获取它 - 之前已经选择的选项不再出现在表单字段中,因为我的查询集仅通过 status=True.

进行过滤

对我来说完美的表单查询集是:

for ForeignKey

当前选择的项目"vessel.slot" + Slot.objects.filter(is_free=True) ?

对于多对多

当前选择的项目"vessel.storage" + Storage.objects.filter(is_free=True) ?

有没有办法完成它?

你可以这样试试:

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)