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

时间:2015-10-15 23:24:11

标签: mysql django django-models django-queryset foreign-key-relationship

**以下是两位模特老师和登录学生,老师可以教多个部分,多个学生可以在同一部分。所以部分字段不能是外键。如果我想找出特定学生所有的课程,我该怎么办?有什么简单的django查询就像sql一样。怎么办? **

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)

1 个答案:

答案 0 :(得分:0)

好的,我建议坚持使用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')

现在回答一个问题,学生参加的课程是什么:

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

希望它有所帮助!