0

我正在尝试自学 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 中迭代课程并获取相关教师?

提前致谢。

4

1 回答 1

0

我不确定这是否完全符合您的要求,但是,这是您想要执行的搜索类型吗?

Membership.objects.filter(type = 1, course__level__name = 'college')

我请了两位老师,他们都是第一类,都教“有趣”的课,一个在“大学”教“有趣”,另一个在“年级”教“有趣”。以下是几次搜索的这些输出:

>>> members = Membership.objects.filter(type=1)
>>> members
[<Membership: Membership object>, <Membership: Membership object>]
>>> members.filter(course__level__name='college')
[<Membership: Membership object>]
>>> Membership.objects.filter(type=1, course__level__name='college')
[<Membership: Membership object>]

也许这个搜索最像你要求的那个:

>>> Membership.objects.filter(course__name='fun', type=1)
[<Membership: Membership object>, <Membership: Membership object>]
于 2013-03-01T16:28:29.807 回答