peewee:过滤从多对多关系中选择查询结果

时间:2013-11-19 13:46:34

标签: python sql orm many-to-many peewee

我有以下代码

#!/usr/bin/env python

"""doc"""

import peewee

db = peewee.SqliteDatabase(":memory:")


class BaseModel(peewee.Model):  # pylint: disable=W0232
    """base model"""

    class Meta:  # pylint: disable=C0111,W0232,R0903
        database = db


class Student(BaseModel):
    """doc"""
    name = peewee.CharField()


class Course(BaseModel):
    """doc"""
    name = peewee.CharField()


class StudentCourse(BaseModel):
    """doc"""
    student = peewee.ForeignKeyField(Student)
    course = peewee.ForeignKeyField(Course)

Student.create_table()
Course.create_table()
StudentCourse.create_table()

s1 = Student(name="Student1")
s1.save()
s2 = Student(name="Student2")
s2.save()
s3 = Student(name="Student3")
s3.save()
s4 = Student(name="Student4")
s4.save()
c1 = Course(name="course1")
c1.save()
c2 = Course(name="course2")
c2.save()
c3 = Course(name="course3")
c3.save()
sc21 = StudentCourse(student=s2, course=c1)
sc21.save()
sc22 = StudentCourse(student=s2, course=c2)
sc22.save()
sc23 = StudentCourse(student=s2, course=c3)
sc23.save()
sc31 = StudentCourse(student=s3, course=c1)
sc31.save()
sc32 = StudentCourse(student=s3, course=c2)
sc32.save()
sc41 = StudentCourse(student=s4, course=c1)
sc41.save()

query = (
    StudentCourse
    .select(StudentCourse, Student, Course)
    .join(Course)
    .switch(StudentCourse)
    .join(Student)
    .order_by(Student.name))

last = None
for student_course in query:
    student = student_course.student
    if student != last:
        last = student
        print "Student: %s" % student.name
    print "    - %s" % student_course.course.name
产生此输出的

Student: Student2
    - course1
    - course2
    - course3
Student: Student3
    - course1
    - course2
Student: Student4
    - course1

这基本上是peewee docs

的例子

我需要过滤结果,只挑选那些拥有特定子集所有课程的学生:

courses = ["course1", "course2"]

我尝试使用 IN 运算符并修改了这样的选择查询:

    query = (
    StudentCourse
    .select(StudentCourse, Student, Course)
    .join(Course)
    .switch(StudentCourse)
    .join(Student)
    .where(Course.name << courses)
    .order_by(Student.name))

但它会产生错误的结果,这意味着我做错了:

Student: Student2
    - course1
    - course2
Student: Student3
    - course1
    - course2
Student: Student4
    - course1

这里有两个错误的事情:

    学生2
  1. course3 未打印,我需要它。我认为这是因为 course3 不在课程列表中。
  2. Student4 被选中,但不应该,因为 Student4 不同时 course1 course2 course1 IN 课程列表。
  3. 是否有可能在一个查询中实现我想要的功能,或者我必须迭代学生,为每个查询做一个 SELECT 查询,并将他们的课程列表与我的相匹配课程过滤?

    我的目标是获得此输出:

    Student: Student2
        - course1
        - course2
        - course3
    Student: Student3
        - course1
        - course2
    

1 个答案:

答案 0 :(得分:-1)