我正在尝试自学 Django 并为教师列表应用程序构建了一个简单的模型。有课程级别(小学、中学、高中等)、课程、教师和教师课程会员资格。
我想获取其教师订阅了特定会员资格的课程级别和课程。目前我正在做以下事情(显然是一个非常糟糕的做法,但由于数据库非常小,它工作正常):
course_levels = CourseLevel.objects.prefetch_related('course_set')
# get mainpage teachers
# TODO: This is inefficient, there must be some cool way of doing the same.
for course_level in course_levels:
for course in course_level.course_set.
course.visible_teachers = course.teachers.filter(membership__type=Membership.TYPE_FRONT_PAGE)
这是models.py
class Teacher(models.Model):
name = models.CharField(max_length=64)
class CourseLevel(models.Model):
name = models.CharField(max_length=64)
class Course(models.Model):
name = models.CharField(max_length=64)
# courses can have levels
level = models.ForeignKey(CourseLevel)
teachers = models.ManyToManyField(Teacher, through='Membership')
class Membership(models.Model):
(TYPE_FRONT_PAGE, TYPE_COURSE_PAGE, TYPE_BASIC) = (1,2,3)
teacher = models.ForeignKey(Teacher, related_name='membership')
course = models.ForeignKey(Course)
MEMBERSHIP_TYPES = (
(TYPE_FRONT_PAGE, _('Front Page')), # Display users on the front page
(TYPE_COURSE_PAGE, _('Course Page')), # Display users on the front of course page
(TYPE_BASIC, _('Basic Membership')), # Display users after
)
type = models.IntegerField(max_length=2, choices=MEMBERSHIP_TYPES)
获取这些记录的更好方法是什么,而不是在 Django Query API 中迭代课程并获取相关教师?
提前致谢。