【问题标题】:Django Edit Form Queryset made of Query + Current Selected Option - How to get?由 Query + Current Selected Option 组成的 Django Edit Form Queryset - 如何获得?
【发布时间】:2015-05-12 03:50:18
【问题描述】:

我的表单.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 字段是 ManytoMany 字段。

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

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

外键

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

多对多

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

有没有办法完成它?

【问题讨论】:

    标签: python django forms django-queryset


    【解决方案1】:

    你可以这样试试:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2013-02-19
      相关资源
      最近更新 更多