class MyFilter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = {
'field': ['exact', 'isnull'],
}
现在我如何过滤这个?field = 1& field__isnull = True ???
答案 0 :(得分:3)
通过添加自定义字段解决了这个问题。
def filter_field_or_null(queryset, value):
return queryset.filter(
Q(field=value) | Q(field__isnull=True)
)
class MyFilter(django_filters.FilterSet):
field_or_null = django_filters.ModelChoiceFilter(
queryset=SomeModel.objects.all(),
action=filter_field_or_null
)
class Meta:
model = MyModel
答案 1 :(得分:0)
我很困惑,你的问题是如何执行OR查询,但是,你的例子是“&” (这通常意味着AND)如果你想制作OR条件,你可以使用Q对象
如:
Q(field=1) | Q(field__isnull=True)
请参阅https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.Q了解详情。
问候。
答案 2 :(得分:0)
供参考使用Django Filter doc
可能是以下示例有用的
from django.db import models
import django_filters
class Mymodel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.IntegerField(null=True)
class MyFilter(django_filters.FilterSet):
field1__iexact = django_filters.CharFilter(lookup_expr='iexact')
field1__isnull = django_filters.CharFilter(lookup_expr='isnull')
class Meta:
model = Product
fields = ['field1']
答案 3 :(得分:0)
您可以使用django-filter 1.1.0查看Customize filtering with Filter.method,代码可以如下所示
class MyFilter(django_filters.FilterSet):
field = NumberFilter(method='field_exact_or_isnull_filter')
class Meta:
model = MyModel
fields = [field]
def field_exact_or_isnull_filter(self, queryset, name, value):
return queryset.filter(
Q(field=1) | Q(field=None)
)