I am trying to "translate" the following SQL statement to SQLalchemy in flask:
select subs.user_id, subs.magazine_id, article.title from article join subs on subs.magazine_id=article.magazine_id and subs.user_id=2;
It works correctly in a mysql shell but when I try to make it work from a plas app I completely fail. Let me explain what I am trying to do: I have three different classes of objects: users, magazines, and articles. A user can be subscribed to many magazines. All articles belong to a unique magazine. Below are the models I use:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column( db.String(64) )
subscriptions= db.relationship('Magazine', secondary=subs, backref=db.backref('subscribers', lazy='dynamic'), lazy='dynamic')
class Magazine(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
articles= db.relationship('Article', backref='magazine', lazy='dynamic')
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(64))
abstract = db.Column(db.String(64))
magazine_id= db.Column(db.Integer, db.ForeignKey('magazine.id'))
subs = db.Table('subs',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('magazine_id', db.Integer, db.ForeignKey('magazine.id'))
)
The subs table is there to keep record of the subscriptions.What I need to do is, for a given user, retrieve all the articles of the magazines to which she is subscribed.
I know how to make it work in python, let's say user1 is a user:
articles=[]
for m in user1.subscriptions:
articles+=m.articles.all()
But I need to do it from SQLAlchemy because I want to filter the articles (read/unread, date of publication, themes ecc) and paginate the results. I can do it from a mysql shell with the statement at the beginning of the post but I fail misarebly when trying to do it from SQLAlchemy:
user1.subscriptions.join(Article).filter(Article.magazine_id==id).all()
gives the error:
AttributeError: 'builtin_function_or_method' object has no attribute 'translate'
Aritcle.c.magazine_idto refer to a column in a result inside the filter, not the column definition in the model.id? Are you sure you're not passing the builtin function of the same name? And why would you filter articles by magazine id at all after joining them to magazines?