因此,在讀取SQLAlchemy ordering by count on a many to many relationship之後,我嘗試複製結果,但它無法正常工作。所以,我的模型,SQLAlchemy通過映射表中的關係排序
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 。發生什麼事了?
有沒有辦法對它們進行排序? – Wiz
通過關係計數 – Wiz
oke doke,即添加 – zzzeek