Django: Как отфильтровать набор запросов по другой модели в django
У меня есть модель Course
и другая модель Video
, которая является внешним ключом к модели Course
. Теперь я хочу сделать следующее: я хочу отобразить все видео, связанные с курсом, и показать видео count
вместе с названием курса в виде списка, а не в детальном представлении.
Вот код, который я написал, но он продолжает показывать ошибку:
The QuerySet value for an exact lookup must be limited to one result using slicing.
views.py
def my_courses(request):
courses = Course.objects.filter(course_creator=request.user)
lectures = Video.objects.filter(course=courses).count()
context = {
'courses': courses,
'lectures':lectures,
}
return render(request, 'dashboard/my_course.html', context)
models.py
class Course(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
course_title = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(unique=True)
course_creator = models.ForeignKey(User, on_delete.models.CASCADE)
class Video(models.Model):
title = models.CharField(max_length = 100 , null = False)
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE)
video_id = models.CharField(max_length = 100 , null = False)
is_preview = models.BooleanField(default = False)
my-courses.html
{% for course in courses %}
<a>{{ course.course_title }}</a>
<a>{{ course.price}}</a>
<td>{{course.video.all.count}} Videos</td>
{% endfor %}
О ваших взглядах:
def my_courses(request):
courses = Course.objects.filter(course_creator=request.user)
context = {
'courses': courses,
}
return render(request, 'dashboard/my_course.html', context)
На ваших шаблонах:
{% for c in courses %}
{% for v in c.video_set.all %}
{{v.title}}
{% endfor %}
{% endfor %}
Например, с помощью этого кода вы перебираете все видеозаписи курсов и получаете название видеозаписи.
РЕДАКТ: Вы можете сделать ваши модели более "дружелюбными к пользователю", добавив "related_name" к модели видео. Таким образом, вы можете получить доступ к видео, просто сделав следующее:
videos_of_a_course = course.videos.all()
В models.py:
class Video(models.Model):
...
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="videos")
....