通过加入不在另一个 table 中的三个 table 来获取记录

Get the records by joining three table that are not in another table

我正在尝试从学生 table 获取记录,条件是学生的主键不存在于 From table 中。(From 用作关系)table。 关系是 "student from department"

型号:

class Student(models.Model):
    name = models.CharField(max_length=20)
    password = models.CharField(max_length=30)
    phone_no = PhoneNumberField(null=False, blank=False, unique=True)
    email = models.EmailField()
    pic_location = models.FileField()
    username = models.CharField(max_length=30)

class From(models.Model):
    s = models.ForeignKey(Student, on_delete=models.PROTECT)
    d = models.ForeignKey(Department,on_delete=models.PROTECT)

class Department(models.Model):
    name = models.CharField(max_length=20)
    password = models.CharField(max_length=30)
    phone_no = PhoneNumberField(null=False, blank=False, unique=True)
    email =  models.EmailField()

我正在尝试在列表视图中获取这些记录。并请检查我检索会话变量的方式是否适用于这种情况??

class PendingStudent(ListView):
# Students pending for department approval
    context_object_name = 'pending_students'
    model = From
    template_name = "admin_panel/department/student_detail.html"

    def get_queryset(self):
        department = self.request.session.get('username')
        return From.objects.filter(~Q(d__name==department))

我使用会话来存储登录的用户类型 (student/teacher/department)。

您似乎想要 return 一个排除某些值的查询集。为此我会使用 .exclude() 而不是 filter 因为它更明确。 您可以检查 here

def get_queryset(self):
    department = self.request.session.get('username')
    queryset = From.objects.exclude(d__name=department)
    # In order to print the SQL query you can do this below
    # print(queryset.query.__str__())
    return queryset

但是,如果您想要 return 许多不在 table 中的学生,您可以这样做:

def get_queryset(self):
    return Student.objects.filter(from__d__isnull=True)

您可以检查 here