Django_select2:如何使用请求数据过滤ModelSelect2Widget queryset? (Django_tables2 + Django_filter + Django_select2)

时间:2019-06-18 11:02:04

标签: python django django-filter django-tables2 django-select2

我根据django_tables2教程将django_tables2与django_filter结合使用:

#views.py
from django_filters.views import FilterView
from django_tables2.views import SingleTableMixin

class FilteredCarListView(SingleTableMixin, FilterView):
    table_class = CarTable
    model = Car
    template_name = 'template.html'    
    filterset_class = CarFilter

def get_queryset(self):
    return self.model.objects.filter(owner_id=request.user.id)

我也想在django_filter中使用django_select2: 我想要一个过滤器的字段及其ModelSelect2Widget,其过滤器与FilteredCarListView.get_queryset(self)中的过滤器相同。

对于过滤器的字段,我找到了这个决定(我想这不是DRY):

# filters.py
from .models import Car
from django_select2.forms import ModelSelect2Widget        

def get_cars(request):  
    return Car.objects.filter(owner_id=request.user.id)

class CarFilter(django_filters.FilterSet):
    car = django_filters.ModelChoiceFilter(
        queryset = get_cars,
        field_name='car',
        widget = ModelSelect2Widget(
        model = Car,
        search_fields=['car__icontains'])       

但是如何将ModelSelect2Widget中的选择限制为仅显示当前用户的汽车?

0 个答案:

没有答案