【问题标题】:How to select records in the case of a many to many relation with ponyorm在与 ponyorm 多对多关系的情况下如何选择记录
【发布时间】:2016-11-05 16:18:41
【问题描述】:

我是 ponyorm 的新手。

假设我有这两个类和它们之间的多对多关系:

class Student(db.Entity):
    id = PrimaryKey(str)
    name = Required(str)
    courses = Set("Course")

class Course(db.Entity):
    id = PrimaryKey(str)
    name = Required(str)
    semester = Required(int)
    students = Set(Student)

我想选择一些特定学生学习的课程。我要做的是:

student = Student.select(lambda s: s.id == id).get()
courses = Course.select(lambda c: c.students == student).get()

我得到这个错误:

Incomparable types 'Set of Student' and 'Student' in expression: c.students == student

这样做的正确方法是什么? 谢谢

【问题讨论】:

    标签: python database ponyorm


    【解决方案1】:

    我不知道确切的库,但我认为问题在于 c.students 指定了所有学生的集合,因此像这样测试相等性并没有太大意义。

    你可能想把你的第二行改成这样(虽然我没有测试过):

    Course.select(lambda c: student in c.students).get()
    

    这让我想知道是否真的有更好的方法来做到这一点。如果您只想检索特定学生参加的课程,为什么不从变量student 中检索courses 字段?

    类似

    student = Student.select(lambda s: s.id == id).get()
    student.courses # do something with it
    

    【讨论】:

    • 你是对的!我可以在student.courses 上进行迭代并得到我需要的东西!
    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多