Search code examples
djangodjango-filter

Django-filter search same foreign key multiple time


I have this in my model

models.py

 class Exercise(models.Model):
     LEVEL_CHOICES = [
         ('0', '0'),
         ('1', '1'),
         ('2', '2'),
         ('3', '3'),
     ]
     level = models.CharField(
         blank=False,
         null=False,
         max_length=1,
         choices=LEVEL_CHOICES
     )
 ...

In my filters.py

class ExerciseFilter(django_filters.FilterSet):
    class Meta:
        model = Execise
        fields = [ 'name', 'tag', 'level' ]

And, finally in my template

<form method="get">
       <div class="row">
         <div class="form-group col">
             <span class="">Name<span>
             {% render_field filter.form.name class="form-control" %}
         </div>
         <div class="form-group col">
             <span class="">Level<span>
             {% render_field filter.form.level class="form-control" %}
         </div>
         <div class="form-group col">
             <span class="">Tags<span>
             {% render_field filter.form.tag class="form-control" %}
         </div>
         
       </div>   </form>

And it's working fine, I can filter my exercises, and see only exercises that are Level 1 for example. it gives me an URL like this

?name=&level=1&tag=

But I would like to be able to get exercise that are level 1 and 2 for example, something like this:

?name=&level=1&level=2&tag=

Can't figure out how to achieve this...


Solution

  • I haven't used django-filter, but based on the docs I think you can use ModelMultipleChoiceFilter. See (this) and (this).