【问题标题】:use django_filters to filter for multiple arguments使用 django_filters 过滤多个参数
【发布时间】:2018-06-01 20:14:03
【问题描述】:

我正在使用 Relay、Django、Graphene Graphql。

我想使用 django_filters 过滤住宿类型的多个参数。这在我的架构文件中有描述,atm 看起来像:

class AccommodationNode(DjangoObjectType) :
    class Meta:
        model = Accommodation
        interfaces = (relay.Node,)
        filter_fields = ['type']

如果我传递一个字符串,例如:{"accommodationType": "apartment"},这将非常有效,但是如果我想过滤所有公寓或酒店,该怎么办?类似:{"accommodationType": ["apartment","hotel"]}

这是我的模型:

class Accommodation(models.Model):
    ACCOMMODATION_TYPE_CHOICES = (
        ('apartment', 'Apartment'),
        ('host_family', 'Host Family'),
        ('residence', 'Residence'),
    )
    school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='accommodations')
    type = models.CharField(
        max_length=200,
        choices=ACCOMMODATION_TYPE_CHOICES,
        default='apartment'
    )
    def __str__(self):
        return str(self.school) + " - " + self.type

有没有什么方法可以做到这一点,而无需像here 建议的那样编写自定义过滤器?对于只有一个过滤器字段,这是一个很好的解决方案,但我最终将在整个应用程序中拥有大约 50 个,包括链接对象...

【问题讨论】:

    标签: django graphql relayjs graphene-python django-filters


    【解决方案1】:

    看看 Django REST 框架过滤器:

    https://github.com/philipn/django-rest-framework-filters

    它不仅支持精确匹配,如您正在寻找的in,还支持exactstartswith 等等,与Django 的ORM 风格相同。我经常使用它并且印象深刻 - 它甚至与 DRF 的 Web 可浏览 API 集成。祝你好运!

    【讨论】:

    • 谢谢!我自己会在答案中给出更多解释:)
    【解决方案2】:

    就像提到的 FlipperPA 一样,我需要使用“in”。根据 django_filter 文档:

    “in”查找返回从基于 CSV 的 BaseInFilter 派生的过滤器。

    以及docs中的BaseInFilter示例:

    class NumberRangeFilter(BaseInFilter, NumberFilter):
        pass
    
    class F(FilterSet):
        id__range = NumberRangeFilter(name='id', lookup_expr='range')
    
        class Meta:
            model = User
    
    User.objects.create(username='alex')
    User.objects.create(username='jacob')
    User.objects.create(username='aaron')
    User.objects.create(username='carl')
    
    # Range: User with IDs between 1 and 3.
    f = F({'id__range': '1,3'})
    assert len(f.qs) == 3
    

    我的问题的答案:

    class AccommodationNode(DjangoObjectType) :
        class Meta:
            model = Accommodation
            interfaces = (relay.Node,)
            filter_fields = {
                'type': ['in']
                }
    

    使用参数{"accommodationType": "apartment,hotel"} 将起作用

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 2015-04-26
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多