我正在使用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个,包括链接对象...
答案 0 :(得分:2)
查看Django REST框架过滤器:
https://github.com/philipn/django-rest-framework-filters
它支持的不仅仅是post build action
,而是in
,exact
,以及更多,与Django的ORM风格相同。我经常使用它并给人留下深刻的印象 - 它甚至可以与DRF的网络浏览API集成。祝你好运!
答案 1 :(得分:2)
'in'lookups返回从基于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"}
将起作用