Simon, thanks for your reply. As I said, I'm not sure that this can be solved on the ORM-level, rather I'm interested in how others solve similar issues. In a small project it's possible to remember what each method is doing internally, but in large ones with dozens of programmers it can be a real problem, hence my question.
On Friday, November 13, 2015 at 12:21:44 PM UTC+2, Simon King wrote: > > On Fri, Nov 13, 2015 at 8:16 AM, Yegor Roganov <yego...@gmail.com > <javascript:>> wrote: > >> Suppose we have a 1 <-> N relation between users and cities (meaning that >> every user is related with one city). For our domain model "User" we want >> to define a method "lives_in_london". Code looks like this: >> >> class User(Base): >> id = ... >> city_id = ... >> city = relationship("City") >> def lives_in_london(self): >> return self.city.name == 'London' >> >> class City(Base): >> id = ... >> name = Column(String) >> >> >> The problem with this code is that "lives_in_london" method is a leaky >> abstraction, its client must keep in mind that it may issue a DB query. >> It's okay as a one-off thing, but will case problems if used in a loop. >> So to be used efficiently, clients must know to preload the "city" >> relationship. >> >> I know it's a contrived example, but the general question is how to >> define domain methods that need to access relations. I also know that the >> question is intrinsic to all ORM, but maybe SQLAlchemy could offer some >> support. >> >> I would appreciate any ideas. >> >> > I'm probably suffering from a lack of imagination here, but this seems > like an impossible task. How could SQLAlchemy know ahead of time whether > you are going to access the "city" property on any given user? And whether > you're going to access it on just one user, or on lots of users in a loop? > > If that's not what you meant, perhaps you could suggest an API that would > do what you wanted? > > Simon > > -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To post to this group, send email to sqlalchemy@googlegroups.com. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.