Python django:根据另一个表上的条件过滤表

时间:2021-09-28 22:21:01

I'm going to filter objects in a table based on whether a field in one of the foreign keys (in another table) contains a string. Consider the following tables:

我将根据其中一个外键(在另一个表中)中的字段是否包含字符串来过滤表中的对象。请考虑以下表格:

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)

I want to have a queryset of students that their teachers name contains 'Sara'. Following code makes the queryset:

我想要一个学生的查询集,他们的老师名字包含'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)

The problem is that this code is very slow.

问题是这段代码很慢。

1 个解决方案

#1


0  

I got it. It was just a row:

我知道了。这只是一排:

student_queryset = Students.objects.filter(Teacher__TeacherName__contains = 'Sara')

#1


0  

I got it. It was just a row:

我知道了。这只是一排:

student_queryset = Students.objects.filter(Teacher__TeacherName__contains = 'Sara')