[英]Flask SQLAlchemy query with order_by returns error no such column
Here is my models:这是我的模型:
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}>'
I`m trying to get persons list ordered by count of pets with this query:我正在尝试使用以下查询获取按宠物数量排序的人员列表:
persons = Person.query.order_by(Person.pets).all()
And getting this error:并收到此错误:
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]
What I`m doing wrong?我做错了什么? I have a suggestion that I need to make a request with join(), but research in google did not give working solutions.我有一个建议,我需要使用 join() 提出请求,但谷歌的研究没有给出可行的解决方案。
If you inspect the SQL, you'll note that there is no FROM item pets
, and so ORDER BY persons.id = pets.owner_id
fails.如果您检查 SQL,您会注意到没有 FROM item pets
,因此ORDER BY persons.id = pets.owner_id
失败。 This happens because the relationship attribute Person.pets
renders as its ON
clause in query context, or in other words as persons.id = pets.owner_id
.发生这种情况是因为关系属性Person.pets
在查询上下文中呈现为其ON
子句,或者换句话说,呈现为Person.pets
persons.id = pets.owner_id
。 There are many ways to form the proper query, for example using a JOIN
and GROUP BY
:有很多方法可以形成正确的查询,例如使用JOIN
和GROUP BY
:
Person.query.\
outerjoin(Person.pets).\
group_by(Person.id).\
order_by(func.count(Pet.id)).\
all()
The LEFT OUTER JOIN
ensures that persons without pets are considered as well. LEFT OUTER JOIN
确保没有宠物的人也被考虑在内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.