我有以下型号。
class Customer(db.Model):
id = db.Column(db.Integer, db.ForeignKey('accounts.id'), primary_key=True)
firstname = db.Column(db.Unicode(128), index=True)
lastname = db.Column(db.Unicode(128), index=True)
account = db.relationship('Account',
backref=db.backref('customer',
uselist=False,
cascade=DEFAULT_WITH_DELETE_CASCADE),
single_parent=True,
cascade=DEFAULT_WITH_DELETE_CASCADE,
foreign_keys=[id])
我想在客户加载时进行帐户表的eagarloading。还有一些我应用于查询的过滤器和连接,然后想要按Customer.id对结果进行分组,以便为客户获得独特的结果。
query = Customer.query.join(Customer.account).options(joinedload(Customer.account))
query = query.order_by(Account.registered_on.desc()).group_by(Customer.id, Account.id)
但是当我在joinloaded之后使用group_by子句时,我得到了错误。如何在joinloaded之后使用group_by?
ProgrammingError: (ProgrammingError) column "accounts_1.id" must appear in the GROUP BY clause or be used in an aggregate function
答案 0 :(得分:0)
我不认为您可以按照您加入的表格中的列进行分组(使用joinedload
)。来自SQLAlchemy docs:The joins produced by orm.joinedload() are anonymously aliased. The criteria by which the join proceeds cannot be modified, nor can the Query refer to these joins in any way, including ordering.
(http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html)
您需要在此处使用常规join
功能,然后使用group_by