Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

One of my fields in my model has a choice field:

STATUS = Choices(
   ('first', _('car')),
   ('second', _('motorcycle')),
   ('third', _('bicycle')),
)

My filter function looks like this:

choice = request.GET.get('choice')

vehicles = vehicles.filter(status=choice).order_by('-date_posted')

The filter works, when I select only one choice, but when I am trying to select more than one choice it only catches the last one selected.

The query looks like that:

?choice=first&choice=second

Any idea how to make it, so it would display items, based on more than one choice?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use .getlist(…) [Django-doc] to obtain the list of options, and then use the __in lookup [Django-doc] to retrieve the vehicles where the status is one of the elements in the list:

choices = request.GET.getlist('choice')

vehicles = vehicles.filter(status__in=choices).order_by('-date_posted')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...