在一个类似的项目中,我使用了 django-autocomplete-light:https ://django-autocomplete-light.readthedocs.io/en/master/tutorial.html ,它可以进行从一个下拉菜单到另一个下拉菜单的级联选择。
我使用它如下:
在 forms.py 中:
class TripModelForm(forms.ModelForm):
plate_number = forms.ModelChoiceField(
queryset=TruckUnit.objects.all().order_by('plate_number'),
widget=autocomplete.ModelSelect2(url='plate_number_autocomplete',
forward=['hauler'])
)
driver = forms.ModelChoiceField(
queryset=Driver.objects.all().order_by('name'),
widget=autocomplete.ModelSelect2(url='driver_autocomplete',
forward=['hauler'])
)
在views.py中:
from dal import autocomplete
class PlateNumberAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return TruckUnit.objects.none()
qs = TruckUnit.objects.all().order_by('plate_number')
hauler = self.forwarded.get('hauler', None)
if hauler:
qs = qs.filter(hauler=hauler)
if self.q:
qs = qs.filter(plate_number__istartswith=self.q)
return qs
class DriverAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Driver.objects.none()
qs = Driver.objects.all().order_by('name')
hauler = self.forwarded.get('hauler', None)
if hauler:
qs = qs.filter(hauler=hauler)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
在 urls.py
urlpatterns += [
path('plate-number-autocomplete/', views.PlateNumberAutocomplete.as_view(), name='plate_number_autocomplete'),
path('driver-autocomplete/', views.DriverAutocomplete.as_view(), name='driver_autocomplete'),
]