使用Django-Filters创建自定义字段
我有一个模型,如下所示。该模型将属性类型
作为外键。
class YachtGeneralInfo(models.Model):
type = models.ForeignKey(
YachtTypes,
related_name="yachts_in_type",
on_delete=models.PROTECT,
blank=False,
null=False,
)
....
....
我编写了这样的视图类 -
class YachtGeneralInfoView(ListAPIView):
pagination_class = PageNumberPagination
serializer_class = YachtGeneralInfoSerializer
filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]
filterset_fields = [
"status",
"is_professional",
"chartered_with__id",
"harbour__id",
"harbour__city__id",
"model__id",
]
search_fields = ["name", "company_name", "website", "owner__name"]
我想为字段type
添加另一个过滤器。但是,我想为此查询参数提供多个值,例如[1,2,3]
。
如果我直接使用QuerySet进行操作,那就是这样 -
queryset = YachtGeneralInfo.objects.filter(type__in=[1,2,3])
有没有办法编写自定义过滤器集字段来完成此操作,而不是直接在QuerySet中将其进行?
I have a model as shown below. The model has the attribute type
as a foreign key.
class YachtGeneralInfo(models.Model):
type = models.ForeignKey(
YachtTypes,
related_name="yachts_in_type",
on_delete=models.PROTECT,
blank=False,
null=False,
)
....
....
I wrote a view class like this -
class YachtGeneralInfoView(ListAPIView):
pagination_class = PageNumberPagination
serializer_class = YachtGeneralInfoSerializer
filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]
filterset_fields = [
"status",
"is_professional",
"chartered_with__id",
"harbour__id",
"harbour__city__id",
"model__id",
]
search_fields = ["name", "company_name", "website", "owner__name"]
I would like to add another filter for field type
. However, I want to provide multiple values for this query parameter like [1,2,3]
.
If I do that directly with queryset then it would be like this -
queryset = YachtGeneralInfo.objects.filter(type__in=[1,2,3])
Is there a way I could write a custom filter set field to accomplish this instead of having it directly in the queryset?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为类型ID查找创建自定义过滤器集。
然后,您可以在视图中设置该类。
You can create your custom filter set for the type id look-up.
Then you can set that class in the view.