有以下形式的模型结构
class Industry(models.Model):
name = models.CharField(max_length=255)
class Category(models.Model):
name = models.CharField(max_length=255)
industry = models.ForeignKey('Industry', null=True, blank=True)
class Franchise(models.Model):
name = models.CharField(max_length=255)
categories = models.ManyToManyField('Category')
industries = models.ManyToManyField('Industry')
我有一个常规过滤器:
class FranchiseFilterSet(django_filters.FilterSet):
industries = django_filters.ModelMultipleChoiceFilter(
queryset=Industry.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
categories = django_filters.ModelMultipleChoiceFilter(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
这个想法是实施一个过滤器,这样当选择行业而不选择其类别时,会显示所选行业的所有特许经营权(没有类别匹配)
我已经实施了额外的过滤器
class CategoryMultipleChoceFilter(django_filters.ModelMultipleChoiceFilter):
def filter(self, qs, value):
categories_list = []
categories_list.extend(value.values_list('id', flat=True))
if value:
industries = self.parent.data.getlist('industries')
for industry_pk in industries:
industry_instance = Industry.objects.filter(pk=industry, category__in=value)
if not industry_instance.exists():
category = Category.objects.filter(industry=industry_pk)
categories_list.extend(category.values_list('id', flat=True))
return super().filter(qs, categories_list)
表示“类别”字段:
class FranchiseFilterSet(django_filters.FilterSet):
...
categories = CategoryMultipleChoceFilter(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
此解决方案有效,但我不确定它是否正确。也许有一个更优雅的解决方案?