django - 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).
解决方案
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
推荐阅读
- python - Starting new Screen on the background on reboot
- azure - Docker 容器在本地运行良好。现在我需要在云端按计划进行
- flutter - Flutter - FutureBuilder 在热重载时触发两次
- angular - Angulars HostListener 干扰了聚焦的 HTML 对象
- security - @code 块中的代码是否已编译并通过浏览器调试可见?
- elrond - 失败:“setState”“newAddresses”字段中的地址应具有 SC 格式:地址:the_crowdfunding_contract
- javascript - 如何使用 Firebase 数据在一个 html 页面中显示多个表格?
- python - 以“pythonic”方式计算与地理坐标的距离
- wordpress - wp远程获取不显示响应卷曲
- python - 使用 R 和 SVD 处理数据集 mnist