我正在使用带有django-rest-framework的django-filter,我正在尝试实例化一个过滤器,该过滤器接受用于过滤查询集的数字列表
class MyFilter(django_filters.FilterSet):
ids = django_filters.NumberFilter(name='id',lookup_type='in')
class Meta:
model = MyModel
fields = ('ids',)
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
filter_class = MyFilter
Run Code Online (Sandbox Code Playgroud)
如果我传入逗号分隔的整数列表,则完全忽略过滤器.
如果我传入一个整数,它会通过django-filter进入django的表单验证器并抱怨:
'Decimal' object is not iterable
Run Code Online (Sandbox Code Playgroud)
有没有办法创建一个django-filter对象,它可以处理整数列表并正确过滤掉查询集?
我使用的是django-rest-framework和https://github.com/alex/django-filter/,但问题主要是关于django-filter.我无法理解如何使用"__in"查找过滤器.
例如,我有模型:
class Book(models.Model):
name = models.CharField(max_length=100)
class BookView(viewsets.ReadOnlyModelViewSet):
serializer_class = BookSerializer()
model = Book
filter_fields = ('id', 'name')
Run Code Online (Sandbox Code Playgroud)
我不能像这样使用网址
/ V1 /书籍/?id__in = 1,2,3
找到id为1,2或3的书籍
使用django-filters,我看到了如何在单个查询字符串中提交多个相同类型参数的各种解决方案,例如多个 ID。他们都建议使用包含逗号分隔值列表的单独字段,例如:
http://example.com/api/cities?ids=1,2,3
Run Code Online (Sandbox Code Playgroud)
是否有使用单个参数但提交一次或多次的通用解决方案?例如:
http://example.com/api/cities?id=1&id=2&id=3
Run Code Online (Sandbox Code Playgroud)
我尝试使用MultipleChoiceFilter,但它期望定义实际选择,而我想传递任意 ID(其中一些甚至可能不存在于数据库中)。
我有一个模型想要过滤多个值。
我的模型:
class Product(models.Model):
ean = models.CharField(max_length=13, unique=True)
product_id = models.CharField(max_length=20, null=True, blank=True)
product_image = models.URLField(max_length=300, null=True, blank=True)
product_title = models.CharField(max_length=300, null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)
我要么想在“ean”字段上进行过滤,要么在主键上进行过滤,两者都可以。根据我当前的设置,我只能看到最后一个值。例如,当我将 URL 构造为www.example.com/api/Product/?id=1&id=2时,我只能看到 id 为 2 的产品,而我想查看 id 为 1 和 id 2 的产品。
我应该如何构建我的 ViewSet?目前我有:
class ProductViewSet(ModelViewSet):
queryset = models.Product.objects.all()
serializer_class = serializers.ProductSerializer
filter_backends = [DjangoFilterBackend]
filter_fields = ('id','ean')
Run Code Online (Sandbox Code Playgroud)