1 # 普通查询 2 q = models.UserInfo.objects.all() 3 for row in q: 4 print(row.name, row.ut.title) # 每次循环时都会去连表查询 5 6 7 # select_related: 查询主动做连表 适合表数据不是特别大 8 q = models.UserInfo.objects.all().select_related('ut') # ut字段是UserInfo表中ForiginKey外键关联字段 9 # 相当于 select * from userinfo inner join usertype on ... 11 for row in q: 12 print(row.name, row.ut.title) # 加了select_related()就不会每次去联表查询了 13 14 15 # prefetch_related: 不做连表, 做多次单表查询 适合表数据非常大 16 q = models.UserInfo.objects.all().prefetch_related('ut') 17 # select * from userinfo 18 # Django内部: ut_id = [2, 4] 把所有的ut_id整合到一个集合做去重 19 # select * from usertype where id in [2, 4] 20 for row in q: 21 print(row.id, row.ut.title)