我想制作一个动态表单来过滤不同的属性,如颜色,大小,品牌等,如何使下面的表单动态化。
我希望如果用户添加另一个属性,那么表单应该自动显示新属性的过滤器
我的硬编码表格如下:
class Att(django_filters.FilterSet):
# I have tried the followigand it is not working
'''q = ProductAttribute.objects.values_list('name',flat=True).distinct()
for item in q:
qw = AttributeChoiceValue.objects.filter(attribute__name=item)
{}.format(item) = django_filters.ModelMultipleChoiceFilter(
queryset=qw.values_list('name', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple)'''
q1 = AttributeChoiceValue.objects.filter(attribute__name='color')
q2 = AttributeChoiceValue.objects.filter(attribute__name='size')
color = django_filters.ModelMultipleChoiceFilter(
queryset=q1.values_list('name', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple)
size = django_filters.ModelMultipleChoiceFilter(
queryset=q2.values_list('name', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple)
class Meta:
model = AttributeChoiceValue
fields = ()
我的模特
class ProductAttribute(models.Model):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=100)
op = models.CharField(max_length=20,default='in')
class Meta:
ordering = ('slug', )
class AttributeChoiceValue(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
attribute = models.ForeignKey(
ProductAttribute, related_name='values', on_delete=models.CASCADE)
class Meta:
unique_together = ('name', 'attribute')