简体   繁体   中英

How to do a JOIN over multiple Django models

The following models are given:

class Copy(CommonLibraryBaseModel):
    lecture = models.ForeignKey('Lecture', ...)
    signature = models.CharField(max_length=100, ...)

class Lecture(CommonLibraryBaseModel):
    category = models.ForeignKey('LectureCategory', ...)

class LectureCategory(CommonLibraryBaseModel):
    parent = models.ForeignKey('self', ...)
    display_name = models.CharField(max_length=100, ...)

I basically want to do the following query:

SELECT signature, display_name FROM lecturecategory as lc, lecture as l, copy as c WHERE lc.id = l.category_id AND c.lecture_id = l.id AND lc.parent_id=2;

How would I do that in Django? I could not figure out how to combine the different models.

Thanks for the help!

SELECT signature, display_name
FROM lecturecategory as lc, lecture as l, copy as c
WHERE lc.id = l.category_id AND c.lecture_id = l.id AND lc.parent_id=2;

will be :

Copy.objects.filter(lecture__category__parent_id=2).values_list('signature', 'lecture__category__display_name')

If you want a QuerSet of dictionnary in result, use values instead of values_list. Values_list return a tuple. Documentation about lookup relationship

You could get a queryset of Copy instances with the following filter

copies = Copy.objects.filter(lecture__category_parent_id=2)

See the docs on lookups that span relationships for more info.

You can then loop through the queryset, and access the related lecture and lecture category using the foreign key.

for copy in copies:
    print(copy.signature, copy.lecture.category.display_name)

Finally, you can change the initial query to use select_related , so that Django uses an inner join to fetch the lecture and category rather than separate queries:

copies = Copy.objects.filter(lecture__category_parent_id=2).select_related('lecture', lecture__category')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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