首页 > 解决方案 > Get the records by joining three table that are not in another table

问题描述

I'm trying the get the records from the Student table, condition is that the student's primary key do not exist in the From table.(From is used as a relation) table. Relation is "student from department"

Model:

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

I'm trying to get those records in the list view. And please review whether the way i'm retrieving session variable is good to go in such case??

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

I've used session, to store what type of user is logged in (student/teacher/department).

标签: djangosessionjoinormrelation

解决方案


It seems that you want to return a queryset which excludes certain values. For that I'd use .exclude() instead of filter since it's more explict. You can check that 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

However, if you want to return many students who are not in the From the table you could do something like:

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

You can check that here


推荐阅读