简体   繁体   English

Django 在同一个查询中得到一对多

[英]Django getting one to many on same query

I need to display a view with Courses with its dependable Lectures on an accordion in html.我需要在 html 中的手风琴上显示带有课程的视图及其可靠的讲座。 A Course has many Lectures.一个课程有很多讲座。

class Course(models.Model):
    title = models.CharField(max_length=1500)
    def __str__(self):
        return self.title

class Lecture(models.Model):
    title = models.CharField(max_length=1500)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    content = models.TextField()

    def __str__(self):
        return self.title

It seems like all the examples I have found.似乎我找到的所有例子都是如此。 Get the relationship after doing a filter or getting the first object like this:在执行过滤器或获取第一个对象后获取关系,如下所示:

Course.objects.first().lecture_set.all()

This gets all the lectures for the first one.这将获得第一堂课的所有讲座。 But I need to get all Courses with all lectures.但我需要获得所有讲座的所有课程。 Something like this:像这样的东西:

Course.objects.all().lecture_set.all() or Course.objects.filter('all').lecture_set.all()

This way I could iterate over Courses and then on each Course iterate again with Course.lectures这样我可以迭代课程,然后在每个课程上再次使用 Course.lectures 迭代

Does anyone know the best practice to achieve this?有谁知道实现这一目标的最佳实践?

You can use prefetch_related() In your example it would be like Course.objects.all(). prefetch_related('lecture_set')您可以使用prefetch_related()在您的示例中,它类似于Course.objects.all(). prefetch_related('lecture_set') Course.objects.all(). prefetch_related('lecture_set') So after that you can iterate all courses and getting its lectures without accessing database. Course.objects.all(). prefetch_related('lecture_set')所以之后你可以迭代所有课程并在不访问数据库的情况下获取它的讲座。 Make sure that you will access it through object itself like:确保您将通过对象本身访问它,例如:

{% for course in courses_list %}
     {% for lecture in course.lecture_set.all() %}

There is good library to inspect each request details, like count of database connections per request.有很好的可以检查每个请求的详细信息,例如每个请求的数据库连接数。 So you can optimize your code.所以你可以优化你的代码。

Hope I hepled.希望我帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM