I have a relationship with the Many-To-Many association database, but the association table itself contains many attributes that need to be accessed, so I made three classes:
class User(Base): id = Column(Integer, primary_key=True) attempts = relationship("UserAttempt", backref="user", lazy="subquery") class Challenge(Base): id = Column(Integer, primary_key=True) attempts = relationship("UserAttempt", backref="challenge", lazy='subquery') class UserAttempt(Base): challenge_id = Column(Integer, ForeignKey('challenge.id'), primary_key=True) user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
This, of course, is a simplified case when I left the other attributes that I need for access. The goal here is that each User can try to execute any number of Challenge s, and therefore, the UserAttempt table, which describes one specific user working with one call.
Now the problem is: when I request for all users and then look at every attempt, I am fine. But when I look at the challenge of this attempt, it explodes in numerous subqueries. Of course, this is bad for performance.
What I really want from SQLAlchemy is to pull out all (or all relevant) calls at once, and then associate them with the corresponding attempts. It does not really matter if all the problems are pulled out or only done, which have the actual association later, since this number of problems is only between 100-500.
My solution right now is not very elegant: I try to parse all the relevant attempts, problems and users, and then connect them manually: Perform all the attempts and assign to add the call and user, then add the call and user to the attempt. This seems to me a cruel decision that should not be necessary.
However, each approach (for example, changing βlazyβ parameters, changed requests, etc.) leads to requests from hundreds to thousands. I also tried to write simple SQL queries that would bring my desired results and came up with something along the lines of SELECT * FROM challenge WHERE id IN (SELECT challenge_id FROM attempts) , and it worked fine, but I can't translate it to SQLAlchemy
Thank you in advance for any recommendations you can offer.