I use django-filter to provide user filtering on a list view on my site, eg
class MyModel(models.Model):
fruit = models.ForeignKey(Fruit)
price = models.CharField(...)
release_date = models.DateTimeField(...)
class MyFilter(filters.FilterSet):
...
class Meta:
model = MyModel
fields = ['fruit', 'price', 'release_date']
def my_banana_orange_view(request):
...
queryset = MyModel.objects.filter(fruit__name__in=['banana', 'orange'])
filter = Filter(request.GET, queryset=queryset)
return render(request, 'my_template.html', {'queryset': queryset, 'filter': filter})
Now if I do this, I can display just the MyModel
entries that have either banana or orange relationships, but MyFilter
will still give the option of all the fruits in the Fruit
model. I'm trying to find a setting for a FilterSet to just show options related to the input queryset, but can't find one. Does one exist?
Otherwise I guess I would have to override the filter to do something like this:
class MyFilter(filters.FilterSet):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.filters['fruit'].extra['queryset'] = Fruit.objects.filter(mymodel=self.queryset)
class Meta:
model = MyModel
fields = ['fruit', 'price', 'release_date']
Which seems a bit overkill. Only showing options based on the input queryset seems like desirable behaviour, but I can't find any documentation for it. Is there a good way to do this? Any help appreciated!
The first param for FilterSet
is data
, the second is queryset
.
Try something along the lines of filter = MyFilter(data=request.GET, queryset=queryset)
in your view.
See: http://django-filter.readthedocs.io/en/develop/guide/usage.html#the-view
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.