django中根据特定的foreignKey查询数据库

时间:2021-05-18 14:58:11

标签: python django django-models

请我有问题查询数据库以获取特定老师下的所有注册学生 模型.py

Type 'WorkerCommandPayload<C> & { command: C; }' is not assignable to type 'CommandAndPayload<LoadLibraryEngineAction, C> | CommandAndPayload<CreateContextEngineAction, C>'.
  Type 'WorkerCommandPayload<C> & { command: C; }' is not assignable to type 'CommandAndPayload<CreateContextEngineAction, C>'.

学生模型.py

class UserProfileInfo(models.Model):

    
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    bio = models.CharField(max_length=500, blank= True)
    teacher = 'teacher'
    admin = 'admin'
    user_types = [
        (teacher, 'teacher'),
        (admin, 'admin'),
        
    ]
    user_type = models.CharField(max_length=10, choices=user_types, default=admin)



    def __str__(self):
        return self.user.username

我已经在数据库中为每个老师注册了一些学生。但是每当我查询数据库以列出特定老师下的所有学生时,我都会得到数据库中的学生列表

这里是views.py

class Student(models.Model):
    userprofile = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE, related_name='myuser')
     
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    profile_pic = models.ImageField(upload_to=student_image, verbose_name="ProfilePicture", blank=True)
    guardian_email = models.EmailField()
    guardian_phone = models.IntegerField()
    
    def __str__(self):
        return self.first_name
    

Student_list .html

class StudentListView(ListView):
    template_name = 'data/student_lis.html'
    queryset = Student.objects.all().order_by("first_name") 
    model= Student

谢谢大家

1 个答案:

答案 0 :(得分:0)

假设访问该视图的用户是老师,并且您想获取该老师的所有学生,您需要覆盖 get_queryset 并在那里返回正确过滤的查询集:

class StudentListView(ListView):
    template_name = 'data/student_lis.html'
    model = Student
    ordering = "first_name"
    
    def get_queryset(self):
        teacher_profile = self.request.user.userprofileinfo # Assuming the user is the teacher
        queryset = super().get_queryset()
        return queryset.filter(userprofile=teacher_profile)
相关问题