Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - Multiple-select form and query django

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?


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

1 Answer

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...