Flask-SQLAlchemy filter_by并遵循多个backrefs

时间:2015-05-17 20:25:44

标签: python flask sqlalchemy flask-sqlalchemy

我想从Flask-SQLAlchemy Quickstart Simple Relationships example扩展架构并添加一个名为Editor的类。

我的架构现在看起来像这样:

from datetime import datetime
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
        backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    editor_id = db.Column(db.Integer, db.ForeignKey('editor.id'))
    editor = db.relationship('Editor',
        backref=db.backref('categories', lazy='dynamic'))

    def __init__(self, name, editor):
        self.name = name
        self.editor = editor

    def __repr__(self):
        return '<Category %r>' % self.name


class Editor(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Editor %r>' % self.name

快速入门示例中的查询,除了按编辑器查询类别外,还可以正常工作:

>>> py = Category('Python')
>>> p = Post('Hello Python!', 'Python is pretty cool', py)
>>> e = Editor('dude')
>>> db.session.add(py)
>>> db.session.add(p)
>>> db.session.add(e)
>>> Post.query.filter_by(category=py).all()
[<Post 'Hello Python!'>]
>>> Category.query.filter_by(editor=e).all()
[<Category 'Python'>]

但是,我还想查找特定编辑器的所有帖子。我尝试使用此查询:

>>> Post.query.filter_by(category.editor=e).all()

但我收到了这个错误:

SyntaxError: keyword can't be an expression

我如何通过编辑获得帖子?

1 个答案:

答案 0 :(得分:2)

您必须首先加入帖子和类别,然后我对您的测试做了一些小修正:

db.create_all()
e = Editor('Dude')
py = Category('Python', e)
p = Post('Hello Python!', 'Python is pretty cool', py)
db.session.add(py)
db.session.add(p)
db.session.add(e)
print Post.query.filter_by(category=py).all()
print Category.query.filter_by(editor=e).all()
print Post.query.join(Category).filter_by(editor=e).all()