这是我的模型:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQLAlchemy(app) class Person(db.Model): __tablename__ = 'persons' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), nullable=False, unique=True) pets = db.relationship('Pet', backref='owner', lazy='dynamic') def __init__(self, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) def __repr__(self): return f'<Person id:{self.id} name:{self.name}>' class Pet(db.Model): __tablename__ = 'pets' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), nullable=False, unique=True) owner_id = db.Column(db.Integer, db.ForeignKey('persons.id'), nullable=False) def __init__(self, *args, **kwargs): super(Pet, self).__init__(*args, **kwargs) def __repr__(self): return f'<Pet id:{self.id} name:{self.name} owner_id:{self.owner_id}>'
我正在尝试通过此查询按宠物计数排序人员列表:
persons = Person.query.order_by(Person.pets).all()
并得到此错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: pets.owner_id [SQL: SELECT persons.id AS persons_id, persons.name AS persons_name FROM persons ORDER BY persons.id = pets.owner_id]
我做错了什么?我建议我需要使用join()进行请求,但是Google的研究并未提供有效的解决方案。
如果检查SQL,则会注意到没有FROM项pets,因此ORDER BY persons.id = pets.owner_id失败。发生这种情况的原因是,关系属性在查询上下文中表示Person.pets为其ON子句,或者表示为persons.id = pets.owner_id。有许多方法可以形成适当的查询,例如使用JOIN和GROUP BY:
pets
ORDER BY persons.id = pets.owner_id
Person.pets
ON
persons.id = pets.owner_id
JOIN
GROUP BY
Person.query.\ outerjoin(Person.pets).\ group_by(Person.id).\ order_by(func.count(Pet.id)).\ all()
的LEFT OUTER JOIN,没有宠物的人被认为是很好保证。
LEFT OUTER JOIN