Here is my models:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class Person(db.Model):
__t
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. 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
. There are many ways to form the proper query, for example using a JOIN
and 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.