Python 我需要在django上运行查询,但无法生成算法

Python 我需要在django上运行查询,但无法生成算法,python,django,django-models,model,Python,Django,Django Models,Model,我在Django有这些模型 class Course(models.Model): Title = models.CharField(max_length=200, unique=True) Card_Title = models.CharField(max_length=200, default='Nothing') Description = RichTextField(blank=True, null=True) Course_Image = models.FileField(upload

我在Django有这些模型

class Course(models.Model):
Title = models.CharField(max_length=200, unique=True)
Card_Title = models.CharField(max_length=200, default='Nothing')
Description = RichTextField(blank=True, null=True)
Course_Image = models.FileField(upload_to='CoursesImages')
Progress = models.IntegerField(blank=True, null=True)
date = models.DateField(default=timezone.now, blank=True)
def __str__(self):
    return self.Title


class Lesson(models.Model):
    Course_id = models.ForeignKey(Course, on_delete=models.CASCADE)
    Number = models.IntegerField()
    Title = models.CharField(max_length=200)
    Completed = models.BooleanField(default=False, blank=True)
    date = models.DateField(default=timezone.now, blank=True)

    def __str__(self):
        return self.Title + ' (' + str(self.Number) + ')'

   

class Topic(models.Model):
    Title = models.CharField(max_length=100)
    Topic = models.FileField()
    Lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
    Completed = models.BooleanField(default=False, blank=True)
    date = models.DateField(default=timezone.now, blank=True)

    def __str__(self):
        return self.Title
工作原理:

  • 每节课都有一门课
  • 所以我们在一门课上有很多课
  • 一个主题可以有一节课
  • 因此,我们在一节课中有许多主题
我需要弄清楚为什么查询是这样的:

{'Lesson1':[Topic1,Topic2,Topic,3,Topic,4],'Lesson':[Topic1,Topic2,Topic,3,Topic,4],........}
必须获取课程ID、相关课程和主题

ans = {}
lessons = course.lesson_set
for lesson in lessions:
  ans[lession.title] = lesson.topic_set