为了账号安全,请及时绑定邮箱和手机立即绑定

Django使用外键进行多次查询

Django使用外键进行多次查询

繁华开满天机 2021-07-08 10:35:28
假设我有两个不同的应用程序:teacher/models.py:  Teacher(models.Model):     name = models.CharField(max_length=300)class/models.py:  Class(models.Model):     name = models.CharField(max_length=300)     teacher = models.ForeignKey(Teacher)     students = models.ManyToManyField(Student)我想让所有的老师上课和所有的课程都附上。我想要的结果:{[   teacher: '3L' #Teachers Id   classes: ['20L','14L','30L'] #list of Class objects or ids with the above teacher],[# similar to above]}这是可能的吗?这就是我目前正在做的事情:classes = Class.objects.all()teachers = Teacher.objects.filter(id__in=classes.value_list('teacher',flat=True).distinct())for teacher in teachers:    classes_for_teachers = classes.objects.filter(teacher=teacher)在上面的代码中,有四个使用循环进行的查询,这无疑增加了时间复杂度。有没有更好的解决方案?提前致谢。

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

使用prefetch_related:


teachers = Teacher.objects.prefetch_related('class_set')


# what you want is not a valid Python structure (set of lists (looking like dicts))

# list of dicts makes more sense

result = [

    {'teacher': t.pk, 'classes': t.class_set.all()}

    for t in teachers

]

无论有多少老师和班级,这只会触发 2 db 查询。


查看完整回答
反对 回复 2021-07-13

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号