StefanE
StefanE

Reputation: 7630

Filter the results from a child table

Been reading the documentation for SQLAlchemy and I cant my head around this. Consider the following setup:

boardset_user_association_table = db.Table('boardset_user_association', 
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('boardset_id', db.Integer, db.ForeignKey('boardset.id'))
)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password = db.Column(db.String(30))
    boardSet = db.relationship('BoardSet', secondary=boardset_user_association_table, backref='user')

    def __repr__(self):
        return "<User('%s','%s')>" % (self.username, self.id)

class BoardSet(db.Model):
    __tablename__ = 'boardset'
    id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime)
    boards = db.relationship('Board', backref='boardset', lazy='dynamic')

    def __repr__(self):
        return "<BoardSet('%s','%s')>" % (self.id, self.created)

I get the collection of items from the User object but I fail performing any filtering etc on the actual data. I would like for example in some situations order the results from User.boardSet by value in field Created

Upvotes: 0

Views: 64

Answers (1)

van
van

Reputation: 76962

Well, you could use lazy='dynamic' also for boardSet, in which case you will get a benefit of

dynamic - the attribute will return a pre-configured Query object for all read operations, onto which further filtering operations can be applied before iterating the results.

class User(...):
    ...
    boardSet = db.relationship('BoardSet', secondary=boardset_user_association_table, backref='user', lazy='dynamic')

myuser = session.query(User).get(1)
boardsets = myuser.boardSet.order_by(BoardSet.created)

Of course, you can easily order the items also in memory after you loaded simply buy doing sorted(myuser.boardSet, key=lambda bs: bs.created)

Upvotes: 1

Related Questions