如何根据另一个表中的数据过滤一个表

时间:2021-05-31 16:43:14

标签: python python-3.x django django-models django-rest-framework

共有三个表:

Sub Copy_Data()
    Dim lastRow As Long, offsetRow As Long, i As Long, No As String, NOSheet As Worksheet, auxRow As Long, summarySheet As Worksheet
    Set summarySheet = Worksheets("Summary")
    lastRow = summarySheet.Columns("A").Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    offsetRow = 7
    For i = 2 To lastRow
        No = Cells(i, "A")
        Set NOSheet = Worksheets(No)
        auxRow = NOSheet.Columns("C").Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
        If auxRow > 1 Then auxRow = auxRow + 2
        If auxRow = 1 Then auxRow = offsetRow
        NOSheet.Cells(auxRow, "C") = summarySheet.Cells(i, "C")
        NOSheet.Cells(auxRow, "D") = summarySheet.Cells(i, "D")
        NOSheet.Cells(auxRow, "E") = summarySheet.Cells(i, "E")
    Next i
End Sub

我想招收不参加特定课程的学生,我满足以下要求

class Course(models.Model):

 name = models.CharField(max_length=255)
 description = models.CharField(max_length=255)
 start_date = models.CharField(max_length=255)
 end_date = models.CharField(max_length=255)

 def get_count_student(self):

   count = CourseParticipant.objects.filter(course=self.id)
   return len(count)

 def __str__(self):
   return f'{self.name}'

class Student(models.Model):

 first_name = models.CharField(max_length=255)
 last_name = models.CharField(max_length=255)
 email = models.CharField(max_length=255)

 def __str__(self):
  return f'{self.first_name}'

class CourseParticipant(models.Model):

 course = models.ForeignKey(Course, related_name='course', on_delete=models.CASCADE)
 student = models.ForeignKey(Student, related_name='student', on_delete=models.CASCADE)
 completed = models.BooleanField(default=False)

我在 pk 中指明课程的 ID,作为回应,我得到:

django.core.exceptions.FieldError:无法将关键字“courseparticipants”解析为字段。选项有:电子邮件、名字、身份证、姓氏、学生

2 个答案:

答案 0 :(得分:0)

由于您没有在 related_name 模型中指定 CourseParticipant,它默认设置为 courseparticipant_set,因此您的查询应该是:

potential = Student.objects.exclude(courseparticipant_set__course=pk)

答案 1 :(得分:0)

related_name相关模型的反向访问器使用的名称,也是默认的相关查询名称。因此,当您在 CourseParticipant 中编写以下内容时:

student = models.ForeignKey(Student, related_name='student', on_delete=models.CASCADE)

这意味着 Student 现在将有一个名为 student 的反向访问器,可用于访问其相关的 CourseParticipant 实例。看看这个,您会意识到您为 related_name 选择了一个错误的(至少在语义上)值。因此,使用此相关名称,您的查询应该是:

potential = Student.objects.exclude(student__course=pk) # Very confusing, yes?

更好的解决方案是将相关名称更改为更合适的名称:

student = models.ForeignKey(Student, related_name='course_participants', on_delete=models.CASCADE)

现在您可以将查询编写为:

potential = Student.objects.exclude(course_participants__course=pk)