Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在多个Django模型上进行连接_Python_Mysql_Django_Join - Fatal编程技术网

Python 如何在多个Django模型上进行连接

Python 如何在多个Django模型上进行连接,python,mysql,django,join,Python,Mysql,Django,Join,给出了以下模型: class Copy(CommonLibraryBaseModel): lecture = models.ForeignKey('Lecture', ...) signature = models.CharField(max_length=100, ...) class Lecture(CommonLibraryBaseModel): category = models.ForeignKey('LectureCategory', ...) class

给出了以下模型:

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, ...)
我基本上想做以下查询:

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;
在Django我该怎么做?我想不出如何组合不同的模型

谢谢你的帮助

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;
将是:

Copy.objects.filter(lecture__category__parent_id=2).values_list('signature', 'lecture__category__display_name')
如果您希望在结果中使用词汇表的查询集,请使用而不是列表中的值。值列表返回一个元组。

将是:

Copy.objects.filter(lecture__category__parent_id=2).values_list('signature', 'lecture__category__display_name')
如果您希望在结果中使用词汇表的查询集,请使用而不是列表中的值。值列表返回一个元组。

您可以使用以下过滤器获得
Copy
实例的查询集

copies = Copy.objects.filter(lecture__category_parent_id=2)
有关更多信息,请参阅上的文档

然后可以循环查询集,并使用外键访问相关的讲座和讲座类别

for copy in copies:
    print(copy.signature, copy.lecture.category.display_name)
最后,您可以将初始查询更改为使用
select_related
,以便Django使用内部联接来获取讲座和类别,而不是单独的查询:

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

您可以使用以下过滤器获得
Copy
实例的查询集

copies = Copy.objects.filter(lecture__category_parent_id=2)
有关更多信息,请参阅上的文档

然后可以循环查询集,并使用外键访问相关的讲座和讲座类别

for copy in copies:
    print(copy.signature, copy.lecture.category.display_name)
最后,您可以将初始查询更改为使用
select_related
,以便Django使用内部联接来获取讲座和类别,而不是单独的查询:

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