【问题标题】:How to combine several models in the one DetailView如何在一个 DetailView 中组合多个模型
【发布时间】:2020-04-17 18:32:39
【问题描述】:

我有 3 个模型 Course、CourseSection、SectionVideo,最后 2 个模型连接到 Course 模型。我想为课程创建 DetailView,它将包含所有模型,我的意思是我可以在其中显示部分内部和内部部分显示视频。该怎么做?

class Course(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=150, null=True, blank=True)
    description = models.TextField()
    image = models.ImageField(upload_to='courses/course_images',blank=True,null=True)
    cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True)
    tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE,null=True)
    students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True)
    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE)
    certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True)
    languages = LanguageField(blank=True)
    rank_score = models.FloatField(default=0.0)
    price = models.FloatField(default=0.0)
    discount_price = models.FloatField(blank=True, null=True)

class CourseSections(models.Model):
    title = models.CharField(max_length=50)
    course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True)

class SectionVideos(models.Model):
    video = models.FileField(upload_to='courses/course_videos',max_length=100)
    section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True)

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以将 DetailView 用于最顶层的实体(您的示例中的课程)https://docs.djangoproject.com/en/3.0/ref/class-based-views/generic-display/

    然后重写get_context_data()并将相关信息添加到上下文中,然后在模板中就可以正常访问了。

    官方文档中的一个例子:https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/#making-friendly-template-contexts

    【讨论】:

    • 谢谢,但是如何准确过滤与确切课程相关的数据,例如课程的部分,部分的视频?)
    • 这将是: get_context 中的 CourseSections.objects.filter(section= section) 据我记得您可以使用以下命令访问 section 对象:self.object 或者您可以查看上下文中的内容超级呼叫并从那里访问它。您获得的视频以相同的方式获得,但您对每个课程的部分进行查找
    • 你能用代码解释一下吗,因为我试过你说的但没有用
    • 你能用你试过的代码编辑你的问题吗?
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2020-05-14
    • 2017-08-26
    • 2013-07-16
    相关资源
    最近更新 更多