0

Making a queryset, but with filters that come from a list

I'm making a flashcard-like web app using django. I have a HTML form with a checklist so the user can select the topics they want to review. The HTML form will pass the selected topics as a list to my python script. chosenTopics = ["topic1", "topic2", "topic3"] In order to retrieve objects from the database that are from "topic1", I used the following: cardList = card.objects.all().filter(cardCategory=chosenTopics[0]) I would get cardList as a queryset. If I wanted objects from topic1 and topic2, I can do it like so: cardList1 = card.objects.all().filter(cardCategory=chosenTopics[0]) cardList2 = card.objects.all().filter(cardCategory=chosenTopics[1]) cardList = cardList1 | cardList2 However, I'm stuck on how I could get a final queryset from all the topics in my chosenTopics list. There are 8 different topics on my HTML form, how can I get a final queryset from any combination of the 8? Any help is greatly appreciated! UPDATE: I messed around and managed to do it with the filter like this: card.objects.all().filter(cardCategory__in=chosenTopics) However, I have no idea why that works. What do the 2 underscores do, and what other operations can I do with them?

8th Jan 2019, 7:24 AM
Daryl
Daryl - avatar
1 Antwort
+ 1
Hi, Good job solving it on your own. This syntax seems totally specific to the Django QuerySet object. I found the documentation of filtering conditions here: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#field-lookups Scroll down to the 'in' section. This is producing a SQL query with a condition something like: SELECT * FROM... WHERE cardCategory IN chosenTopics
8th Jan 2019, 2:24 PM
Tibor Santa
Tibor Santa - avatar