I'm using Django rest Framework together with django_filters. (I've tried to simplify/reduce the code here as much as possible)

How can I force django_filters to filter for constraints__name=None (or constraints=None) if no constraint is specified in the request?

Let's say I have this model:

class Resource(models.Model): constraints = models.ManyToManyField(Feature, related_name='constraint+', blank=True) class Feature(models.Model): name = models.CharField(max_length=255, blank=False, unique=True)

And this view and filter:

class ResourceFilter(FilterSet): constraints = django_filters.CharFilter(name='constraints__name') class Meta: model = Resource fields = ['constraints'] class ResourceViewSet(viewsets.ModelViewSet): serializer_class = ResourceSerializer filter_class = ResourceFilter filter_backends = (filters.DjangoFilterBackend,)

/api/resource/?constraints=testconstraint works fine, but I want /api/resource/ to only return the Resources that have no constraints.

I can reduce the queryset, but it feels like something django_filters could solve. Is it?:

def get_queryset(self): if 'constraints' not in self.request.query_params: return Resource.objects.filter(constraints=None) else: return Resource.objects.all()

You can override the qs property on the FilterSet subclass, where you can manipulate the filtered query and access the request object:

Try with this:

class ResourceFilter(FilterSet): constraints = django_filters.CharFilter(name='constraints__name') class Meta: model = Resource fields = ['constraints'] @property def qs(self): parent_qs = super(ResourceFilter, self).qs if 'constraints' in self.request.query_params: return parent_qs else: return parent_qs.filter(constraints=None)

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

代码区博客精选文章
分页:12
转载请注明
本文标题:Django Rest Framework + django_filter: filte ...
本站链接:https://www.codesec.net/view/627858.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(40)