通过联接不在另一个表中的三个表来获取记录

时间:2019-06-05 12:26:37

标签: django session join orm relation

我正在尝试从Student表中获取记录,条件是在From表中不存在学生的主键。(From用作关系)表。 关系是“系学生”

型号:

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))

我已经使用会话来存储登录的用户类型(学生/教师/部门)。

1 个答案:

答案 0 :(得分:0)

似乎您想返回一个排除某些值的查询集。为此,我将使用.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

但是,如果您想归还许多不在表格中的学生,则可以执行以下操作:

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

您可以检查here