我将根据其中一个外键(在另一个表中)中的字段是否包含字符串来过滤表中的对象。请考虑以下表格:
class Students(models.Model):
StudentID = models.SmallIntegerField(primary_key=True)
Teacher = models.ForeignKey(Teachers)
class Teachers(models.Model):
TeacherID = models.SmallIntegerField(primary_key=True)
TeacherName = models.CharField(max_length=20)
我想要一个学生的查询集,他们的老师名字包含'Sara'。以下代码生成查询集:
student_queryset = Students.objects.all()
for student in student_queryset:
if str(student.Teacher.TeacherName).find('Sara') == -1:
student_queryset = student_queryset.exclude(StudentID = student.StudentID)
问题是这段代码非常慢。
答案 0 :(得分:0)
我明白了。这只是一排:
student_queryset = Students.objects.filter(Teacher__TeacherName__contains = 'Sara')