【问题标题】:How to filter a table based on data from another table如何根据另一个表中的数据过滤一个表
【发布时间】:2021-05-31 16:43:14
【问题描述】:

共有三个表:

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)

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

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

我在 pk 中表示课程的 id,作为回应,我得到:

django.core.exceptions.FieldError:无法将关键字“课程参与者”解析为字段。选项包括:电子邮件、名字、id、姓氏、学生

【问题讨论】:

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


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • Student.objects.exclude(courseparticipant_set__course=pk) 我仍然得到答案 django.core.exceptions.FieldError: Cannot resolve keyword 'courseparticipant_set' into field。选项包括:电子邮件、名字、身份证、姓氏、学生
      • 我不知道该怎么办
      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多