我的回答受到
this
一个。
如果我的解释正确,我认为问题的关键在于你要找的课程有一个学生,但没有指派指导老师,在这个课程的学生之间有一个交叉点。
genres
还有教练的
体裁
.
我添加了
student
和
instructor
你的关系
Lesson
补充模型
Foreign Keys
您已经创建了,这使我更容易生成一些测试数据,如果没有其他内容:
class Lesson(db.Model):
id = db.Column(db.Integer, primary_key=True)
instructor_id = db.Column(db.Integer, db.ForeignKey("instructor.id"))
student_id = db.Column(db.Integer, db.ForeignKey("student.id"))
student = db.relationship(Student, uselist=False, backref='lessons')
instructor = db.relationship(Instructor, uselist=False, backref='lessons')
以下是我生成的测试数据:
import random
db.drop_all()
db.create_all()
# create a set of tags
tags = [Tag(genre=g) for g in ('Jazz', 'Funk', 'Rock', 'Classical', 'Metal')]
# create 10 students with 2 tags randomly assigned
students = [Student(genres=random.sample(tags, 2)) for _ in range(10)]
# create 2 instructors with 2 tags randomly assigned
instructors = [Instructor(genres=random.sample(tags, 2)) for _ in range(2)]
# create a lesson for each student
lessons = [Lesson(student=s) for s in students]
db.session.add_all(tags + students + instructors + lessons)
db.session.commit()
然后,为了查询,我查询
课
加入
Student
和
student_tag_association_table
以便我能找到
课
具有
instructor_id == None
和A
学生
用一个
tag_id
它符合
Instructor's
链接的
tag_ids
:
# randomly select an instructor
instructor = random.choice(instructors)
possible_lessons = db.session.query(Lesson).\
join(Student).\
join(student_tag_association_table).\
filter(and_(Lesson.instructor_id == None,
or_(
student_tag_association_table.c.tag_id.in_(
g.id for g in instructor.genres
)
)
)).all()
然后测试:
for lesson in possible_lessons:
try:
assert any([g in lesson.student.genres for g in instructor.genres])
except AssertionError:
print('uh oh')
else:
print('yes')
# yes
# yes
# yes
# yes
# yes
由于测试数据是随机的,您将得到不同数量的
yes
每次输出。