我有三个sqlalchemy表,如下所示。 Categories-feeds是一个多关系,feed-articles是一对多的关系。
我想要做的是通过查询Category对象来访问类别提要的文章。类似的东西:
Category.query.get(1).articles
如何使用以下代码?
category_feeds = db.Table('category_feeds',
db.Column('feed_id', db.Integer, db.ForeignKey('feed.id')),
db.Column('category_id', db.Integer, db.ForeignKey('category.id'))
)
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text)
content = db.Column(db.Text)
href = db.Column(db.Text)
feed_id = db.Column(db.Integer, db.ForeignKey('feed.id'))
class Feed(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text)
xml_url = db.Column(db.Text)
html_url = db.Column(db.Text)
articles = db.relationship('Article', backref='feed')
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
setattr(self, key, value)
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text)
feeds = db.relationship('Feed', secondary=category_feeds,
backref=db.backref('categories'))
articles = ???
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
setattr(self, key, value)
答案 0 :(得分:3)
您可以在Category
类上添加一个属性,该属性将运行您需要的查询:
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text)
feeds = db.relationship('Feed', secondary=category_feeds,
backref=db.backref('categories'))
@property
def articles(self):
this_category = Category.query.get(self.id)
articles = db.session.query(Article).join(Article.feed).filter(Feed.categories.contains(this_category))
return articles
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
setattr(self, key, value)
有了这个,你可以简单地说:
articles = Category.get(1).articles
print [x.title for x in articles]