2016-11-05 85 views
1

我是新來的ponyorm。如何在與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 

什麼是做到這一點的正確方法是什麼? 謝謝

回答

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 
+0

你是對的!我可以遍歷'student.courses'並獲得我需要的! – gaetano

相關問題