0

**以下是老師和登錄學生的兩種模式,一位老師可以教多個部分,多個學生可以在同一部分。因此部分字段不能是外鍵。如果我想查明所有的課程都是由某個學生完成的,我該怎麼做?是否有任何簡單的django查詢就像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) 
+0

你有沒有試過做這件事。 – CurseStacker

+0

你應該檢查https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model – cdvv7788

+0

@CurseStacker newobj = teacher.objects.raw('select * from app_teacher t,app_loginstudent l其中l.section = t.section和l.username =%s',[name])..name是學生姓名,我想列出其姓名 –

回答

0

OK,我會建議堅持從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]) 

希望它有幫助!