Amin
Amin

Reputation: 2043

how to query inside a class in sqlalchemy

I have a User class with a one-to-many relationship to the Item class:

class User(Base):
    items=relationship(Item)
    def method(self):
        for item in self.items
            if self.items.itemname=='my item'
                #do something

Now I want to get access of some of the items (filtered) of a User in a method inside the User class. Is it more efficient (performance wise) to write a for-loop running over all the items (as it is in the example) or to run a query inside the class? (let's say there are a couple of thousands of items for an average user). I also don't know how I can even run a query inside a class! Is there anything like self.query.filter() way or I should define a session inside the class and run session.query(Items).filter()?

Upvotes: 4

Views: 4288

Answers (1)

schlamar
schlamar

Reputation: 9511

If you are certain that the current instance is attached to a session you can get it with sqlalchemy.orm.session.object_session

So it will be:

from sqlalchemy.orm.session import object_session

class User(Base):
    ...

    def method(self):
        session = object_session(self)
        session.query(Items).filter(...)

Edit:

As alternative I can suggest Dynamic Relationship Loaders. In this case you get the relationship as a query which can be further defined:

class User(Base):
    items=relationship(Item, lazy='dynamic')

user1 = session.query(User).get(user_id)
user1.items.filter(...)

Upvotes: 8

Related Questions