Django 过滤具有相同选择的多个字段
Django filter multiple fields with same choices
我有一个看起来像这样的模型:
field_1 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)
field_2 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)
我想用 django_filters 创建一个过滤器,以将这 2 个单独的字段组合成 1 个 ChoiceFilter。我该怎么做?
您可以指定用于过滤自定义字段的方法:
class YouFilter(FilterSet):
new_field = ChoiceFilter(method='filter_new_field', choices=FIELD_CHOICES)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'new_field')
def filter_new_field(self, queryset, name, value):
return queryset.filter(
field_1=value,
field_1=value
)
我有一个看起来像这样的模型:
field_1 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)
field_2 = models.IntegerField(choices=FIELD_CHOICES, blank=True, null=True)
我想用 django_filters 创建一个过滤器,以将这 2 个单独的字段组合成 1 个 ChoiceFilter。我该怎么做?
您可以指定用于过滤自定义字段的方法:
class YouFilter(FilterSet):
new_field = ChoiceFilter(method='filter_new_field', choices=FIELD_CHOICES)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'new_field')
def filter_new_field(self, queryset, name, value):
return queryset.filter(
field_1=value,
field_1=value
)