gaetano
gaetano

Reputation: 907

How to select records in the case of a many to many relation with ponyorm

I am new to ponyorm.

Suppose I have these two classes and a many-to-many relation among them:

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)

And I want to select some courses which are followed by a particular student. What I do is:

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

And I get this error:

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

What is the correct way to do this? Thanks

Upvotes: 3

Views: 232

Answers (1)

evotopid
evotopid

Reputation: 5429

I don't know the exact library but I think the issue is that c.students specifies the set of all students so testing for equality just like that doesn't make too much sense.

You might want to change your second line to something like this (I didn't test it though):

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

This leaves me wondering if there is actually a better way to do this. If all you are trying is to retrieve the courses a specific students attends why don't you just retrieve the courses field from the variable student?

Something like

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

Upvotes: 1

Related Questions