Skip to content
Advertisement

Django Query Multi Table

I’m trying to do a form query on a field and the goal is to get all the kids enrolled in all the teachers classes in this drop down menu. The query I have right now is getting all the classes a teacher is enrolled in . However how do I retrieve the kids within those classes. I attached a picture to so you can visually see how I linked the tables.

FORMS.PY

class Select_Student_Phone_Log_Form(forms.ModelForm):
    class Meta:  
            model = PhoneLog       
            fields = ('student_ps',)
            labels = {'student_ps':_('Student Name') }     

    def __init__(self, *args, **kwargs): 
        self.user = kwargs.pop('user')   
        super (Select_Student_Phone_Log_Form,self).__init__(*args,**kwargs )  
        students = SectionEnrollment.objects.filter(section_id__teacher_username = self.user)
        self.fields['student_ps'].queryset= students

MODELS.PY

# Section Information Stored
class Section(models.Model):
    sectionpsid= models.CharField(primary_key = True, default = "", max_length = 50)
    schoolpsid = models.ForeignKey(School,on_delete = models.CASCADE, default = "" ,)
    coursepsid = models.ForeignKey(Course,on_delete = models.CASCADE, default = "" ,) 
    termpsid = models.ForeignKey(Term,on_delete = models.CASCADE, default = "" ,) 
    section_number = models.CharField(default = "", max_length = 50)
    expression = models.CharField(default = "", max_length = 50)
    external_expression= models.CharField(default = "", max_length = 50)
    staffpsid = models.ForeignKey(Staff,on_delete = models.CASCADE, default = "" ,) 
    gradebooktype = models.CharField(default = "", max_length = 50)
    teacher_username = models.ManyToManyField(User)

    # Creation of Classrooms and Assigned Teachers 
class SectionEnrollment(models.Model):
    sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "")
    section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,)
    studentpsid = models.ForeignKey(Student,on_delete = models.CASCADE, default = "" ,)
    entry_date = models.DateField(blank=True)
    exit_date = models.DateField(blank=True)
    dropped = models.BooleanField(default = False, blank = True)
    
    

# Where Basic Student Data Is Stored 
class Student(models.Model):
    studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    first_name = models.CharField(max_length = 50, default = "")
    last_name = models.CharField(max_length = 50,default = "")
    gender = models.CharField(max_length = 1,default = "")
    student_grade = models.CharField(max_length = 2, default = "")
    home_room = models.CharField(max_length = 5, default = "")
    student_enrollment = models.CharField(max_length = 2, default = "")
    school_number = models.CharField(max_length = 15, default = "") 
    email = models.EmailField(default = "")
    projected_graduation_year = models.CharField(max_length = 4, default = "")
    counseling_goal = models.TextField(max_length = 255)
    win_username = models.CharField(max_length = 50)
    win_password = models.CharField(max_length = 50)
    offsite_laptop = models.BooleanField(default = False, blank = True)
    image = models.ImageField(default ="default.png", upload_to ='student_pics')

# Stores Phone Log Information
class PhoneLog(models.Model):
    student_ps = models.ForeignKey(Student,on_delete = models.CASCADE, default ="") 
    created_at = models.DateTimeField(default = timezone.now) 
    comments = models.TextField(max_length = 355, default= "")
    RESULT_CHOICES = [
        (None, 'PLEASE SELECT A RESULT'),  # THIS IS OPTIONAL
        (1, 'Spoke to Mom'),
        (2, 'Spoke to Dad'),
        (3, 'Spoke to Guardian'),
        (4, 'Left message'),
        (5, 'Messages Full'),
        (6, 'Sent Email'),
        (7, 'Other'),
    ]
    result = models.PositiveSmallIntegerField(choices = RESULT_CHOICES)
    created_by = models.ForeignKey(User, on_delete = models.PROTECT)

    class Meta:
        verbose_name = "K8-Phone Log"

    def __str__(self):
        return self.student_ps.student_name    

Table Relationships Error Message

Advertisement

Answer

I would try this :

class Select_Student_Phone_Log_Form(forms.ModelForm):
    class Meta:  
        model = PhoneLog       
        fields = ('student_ps',)
        labels = {'student_ps':_('Student Name') }

    def __init__(self, *args, **kwargs): 
        self.user = kwargs.pop('user')   
        super(Select_Student_Phone_Log_Form, self).__init__(*args, **kwargs )  
        self.fields['student_ps'].queryset = Student.objects.filter(sectionenrollment__section__teacher_username=self.user)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement