how to select some value from multiple table in Django?

Question:

I want to to select some students from table A where students username and class code are not inside table B. So it will show all student that not inside the student class list yet.

the query was like

SELECT students from TableA WHERE username NOT IN tableB AND classcode = CODE

models.py

class modelStudentclassss m(models.Model):
    classcode = models.CharField(max_length=200, null=False, blank=False)
    username = models.CharField(max_length=200, null=False, blank=False)
class modelUser(models.Model):
    username = models.CharField(max_length=200, null=False, blank=False)

views.py

studentclass = modelStudentclass.objects.all()
studentdata = modelUser.objects.exclude(studentusername = studentclass.username).filter(role="student", classcode=classcode)
Asked By: Albert Wijaya

||

Answers:

You can work with:

Studentclass.objects.exclude(username__in=User.objects.values('username')).filter(
    classcode=code
)

Note: Models normally have no Model… prefix. Therefore it might be better to rename modelUser to User.


Note: Specifying null=False [Django-doc] is not necessary: fields are by default not NULLable.


Note: Specifying blank=False [Django-doc] is not necessary: fields are by default not blank and thus are required by a form.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.