'How to filter all child objects by value of parent class of parent in SQLAlchemy in flask application
I have simple flask application with following relations between models.
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'),
nullable=False)
category = db.relationship('Category',
backref=db.backref('posts', lazy=True))
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'),
nullable=False)
post = db.relationship('Post',
backref=db.backref('comments', lazy=True))
Category has posts and posts have comments. When i try to filter all comments based on post names with following query
post_names = ["First post", "Second post"]
db.session.query(Comment).filter(Comment.post.has(Post.name.in_(post_names))).all()
then i am receiving correct results. However when I try to find all comments for specific category with following query
category_names = ["Python"]
db.session.query(Comment).filter(Comment.post.category.has(Category.name.in_(category_names))).all()
then I am receiving following error
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Comment.post has an attribute 'category'
How could I solve this? I would like to avoid Joins as i can not call delete on the query then
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
