S
S
Sergey Nizhny Novgorod2016-10-12 02:21:17
Django
Sergey Nizhny Novgorod, 2016-10-12 02:21:17

How to select elements from a list in Django?

Hello.
There is a task:
The article has a list of tags, the course has a tag (one) = you need to pick up all courses from the database that have a common tag with articles.
tags = Tag.objects.filter(tags=article_id) = retrieves all tags that belong to this article (a list of all tags).
course_handler = Course.objects.filter(tags_for_course=tags) = this thing only searches for the first tag. (the rest of the list is not taken into account).
How to write a query so that all courses in the list are selected.
You can, of course, do something like this, but it looks kind of wild.

course_handler = []
for tag in tags:
    course_ready = Course.objects.filter(tags_for_course=tag)
    course_handler.append(course_ready)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Nizhny Novgorod, 2016-10-12
@Terras

Found the solution on this page:
https://docs.djangoproject.com/en/1.10/topics/db/q...

course_handler = Course.objects.filter(tags_for_course__in=tags)
.
The __in tail makes it possible to loop through the list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question