Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
django-Filter: Only show filter options contained in queryset

I'm using the excellent [django-filter](https://github.com/carltongibson/django-filter) app to filter a queryset of model objects. Let's say my model and view look as follows:

#model
[...]
class Animal(models.Model):
REGION_CHOICES = (
(0, 'Africa'),
(1, 'Europe'),
)

name = models.CharField(max_length=100)
region = models.CharField(choices=REGION_CHOICES, max_length=100)
[...]

#view
[...]
qs = Animal.objects.all()
filter = AnimalFilter(request.GET, qs)
[...]


Assuming there are two animals in the database:

zebra = Animal(name='Zebra', region='Africa')
frog = Animal(name='Frog', region'Europe')

When I render the filter in the template, I correctly get a selector for region which contains the two options Europe and Africa.

But if I use some logic in the view to .exclude() objects from the queryset like this:

#view
[...]
qs = Animal.objects.all().exclude(name='Frog')
filter = AnimalFilter(request.GET, qs)
[...]

Now if I render the filter in the template I still get the two optione Europe and Africa for region although the queryset only contains one animal which has the region Africa.

Any ideas how I could get the correct options for the region field rendered in the template? Any help is greatly appreciated.

/r/djangolearning
https://redd.it/7d32ck