使用ForeignKey和ManyToMany查询Django模型

时间:2013-03-01 14:46:57

标签: django

我正在尝试自学Django并为教师列表应用程序构建了一个简单的模型。有课程水平(小学,中学,高中等),课程,教师和教师课程会员。

我想获取课程水平&教师订阅特定会员资格的课程。目前我正在关注(显然是一种非常糟糕的做法,但由于DB非常小,它正常工作):

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中迭代课程和获取相关教师?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我不确定这究竟能回答你想要的东西但是,这是你想要做的搜索类型吗?

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

我做了两位老师,他们都是1型,都教授课堂“有趣”,还有一位在“大学”教授“有趣”的老师和另一位在“年级”教授“有趣”的老师。以下是一些搜索的输出:

>>> 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>]