Flask SQLAlchemy query with order_by returns error no such column

后端 未结 1 1927
谎友^
谎友^ 2021-01-28 04:03

Here is my models:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
db = SQLAlchemy(app)


class Person(db.Model):
    __t         


        
相关标签:
1条回答
  • 2021-01-28 04:37

    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.

    0 讨论(0)
提交回复
热议问题