Django:如何筛选下拉框Lot为所属同项目的批次
问题:Django下拉框选项筛选限制需求
我在处理下拉框选项筛选时遇到问题,需要限制"Lot"下拉框仅显示与当前Institute所属同一Project的Lot,相关信息如下:
ERM模型图

模板截图

当前视图代码
class EquipmentinLocationAdd(CreateView): model = EquipmentInLocation form_class = EquipmentAddToLocationForm template_name = 'Procure/equipmentinlocation_add.html' def get_success_url(self): return reverse('equipmentinlocation_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial
需实现筛选"Lot"下拉框,仅展示与当前选中Institute同属一个Project的Lot,求解决方案。
解决方案
提供两种可行实现方式,根据你的代码复用需求选择:
方式一:直接在视图中修改表单查询集
在EquipmentinLocationAdd类中新增get_form方法,通过当前Institute关联的Project过滤Lot选项:
class EquipmentinLocationAdd(CreateView): model = EquipmentInLocation form_class = EquipmentAddToLocationForm template_name = 'Procure/equipmentinlocation_add.html' def get_success_url(self): return reverse('equipmentinlocation_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get(id=self.kwargs['pk']) initial = {'Institute': qs} return initial def get_form(self, form_class=None): form = super().get_form(form_class) # 获取当前Institute对象 institute = Institute.objects.get(id=self.kwargs['pk']) # 筛选同Project下的Lot form.fields['Lot'].queryset = Lot.objects.filter(Project=institute.Project) return form
方式二:通过表单类接收参数实现复用
如果该表单需要在其他场景复用,可在表单类中添加初始化逻辑,接收Institute参数过滤Lot:
- 修改表单类:
class EquipmentAddToLocationForm(forms.ModelForm): class Meta: model = EquipmentInLocation fields = ['Institute', 'Lot'] # 补充你的其他字段 def __init__(self, *args, **kwargs): # 取出传入的institute参数 self.institute = kwargs.pop('institute', None) super().__init__(*args, **kwargs) # 存在institute时过滤Lot查询集 if self.institute: self.fields['Lot'].queryset = Lot.objects.filter(Project=self.institute.Project)
- 在视图中传递institute参数:
class EquipmentinLocationAdd(CreateView): # 保留原有方法 def get_form(self, form_class=None): institute = Institute.objects.get(id=self.kwargs['pk']) return self.form_class(institute=institute, **self.get_form_kwargs())
注意事项
确保你的Institute模型包含Project外键字段,Lot模型也包含Project外键字段,否则过滤逻辑无法生效。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

