flask-sqlalchemy 三向关联

flask-sqlalchemy three way association

我有如下三个 sqlalchemy 表。 Categories-feeds 是多对多的关系,feeds-articles 是一对多的关系。

我想做的是能够通过查询类别对象来访问类别提要的文章。类似于:

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)

您可以在 Category class 上添加一个 属性,这将 运行 您需要的查询:

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]