因此,在阅读SQLAlchemy ordering by count on a many to many relationship之后,我尝试复制结果,但它无法正常工作。所以我的模型是
class Group(Base):
__tablename__='groups'
__table_args__={
'mysql_engine':'InnoDB',
'mysql_charset':'utf8',
}
id = Column(Integer, primary_key=True, unique=True)
name = Column(VARCHAR(30), primary_key=True, unique=True)
time = Column(DateTime, onupdate = datetime.datetime.now)
description = Column(VARCHAR(255))
creator_id = Column(Integer, ForeignKey('users.id'))
privacy = Column(SMALLINT) # 0 == public, 1 == friends, 2 == private
def __init__(self, name, descr, creator, privacy):
self.name = name
self.description = descr
self.creator_id = creator
self.privacy = privacy
class GroupUserRelationship(Base):
__tablename__='groupUserRelationships'
__table_args__={
'mysql_engine':'InnoDB',
'mysql_charset':'utf8',
}
id = Column(Integer, primary_key = True)
group_id = Column(Integer, ForeignKey('groups.id'))
user_id = Column(Integer, ForeignKey('users.id'))
time = Column(DateTime, onupdate=datetime.datetime.now)
def __init__(self, group, user):
self.group_id = group
self.user_id = user
我的 sqlalchemy 查询是groups = session.query(Group, func.count(GroupUserRelationship.user_id).label('total')).join(GroupUserRelationship).group_by(Group).order_by('total DESC').limit(20).all()
,但是当我尝试遍历它返回的列表并访问组 id 时,我得到一个 AttributeError:'NamedTuple' 没有属性 id。怎么了?