gpt4 book ai didi

mysql - 没有外键的简单 django 连接查询

转载 作者:行者123 更新时间:2023-11-29 21:55:55 24 4
gpt4 key购买 nike

** 下面有两个模型teacher和loginstudent,一个老师可以教多个部分,多个学生可以在同一个部分。所以部分字段不能是外键。如果我想找出特定学生修读的所有类(class),我应该怎么办?有没有像sql一样简单的django查询。怎么做?**

class Teacher(models.Model):
username=models.CharField(max_length=50)
password=models.CharField(max_length=89)
course=models.CharField(max_length=30)
section=models.CharField(max_length=30)

class LoginStudent(models.Model):
username=models.CharField(max_length=50)
password=models.CharField(max_length=89)
section=models.CharField(max_length=30)

最佳答案

好的,我建议坚持使用 Django 的默认用户系统,并在需要时构建特定类型的一对一配置文件。稍后您可以根据外键的值区分用户,或者您可以实现与用户类型相关的权限

from django.db.models.query_utils import Q


# for example, this could be a way to extend users to hold teachers and students
class TeacherProfile(models.Model):
user = models.OneToOneField(User, related_name='teacher_profile')
# other relevant teacher profile items
ONLY_TEACHERS_FILTER = Q(teacher_profile__isnull=False) & Q(student_profile__isnull=True)


class StudentProfile(models.Model):
user = models.OneToOneField(User, related_name='student_profile')
# other relevant student profile items
sections = models.ManyToManyField('Section', related_name='students') # mind the quotes to Section name


class Section(models.Model)
name = models.CharField(max_length=50)
# other section fields goes here...


class Course(models.Model):
name = models.CharField(max_length=50)
teacher = models.ForeingKey(User, related_name='courses', limit_choices_to=ONLY_TEACHERS_FILTER)
sections = models.ManyToManyField(Section, related_name='courses')

现在回答学生参加哪些类(class)的问题:

queryset = Course.objects.filter(section__students__in=[user])

希望对你有帮助!

关于mysql - 没有外键的简单 django 连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33160145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com