from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import TIMESTAMP
from sqlalchemy.orm import relationship
BaseModel = declarative_base()
class Base(BaseModel):
__tablename__ = 'base'
id = Column(Integer, primary_key=True)
location = Column(Unicode(12), ForeignKey("locationterrain.location"), unique=True,)
name = Column(Unicode(45))
ownerid = Column(Integer,ForeignKey("player.id"))
occupierid = Column(Integer, ForeignKey("player.id"))
submitid = Column(Integer,ForeignKey("player.id"))
updateid = Column(Integer,ForeignKey("player.id"))
owner = relationship("Player",
primaryjoin='Base.ownerid==Player.id',
join_depth=3,
lazy='joined')
occupier= relationship("Player",
primaryjoin='Base.occupierid==Player.id',
join_depth=3,
lazy='joined')
submitter = relationship("Player",
primaryjoin='Base.submitid== Player.id',
join_depth=3,
lazy='joined')
updater= relationship("Player",
primaryjoin='Base.updateid== Player.id',
join_depth=3,
lazy='joined')
class Player(BaseModel):
__tablename__ = 'player'
id = Column(Integer, ForeignKey("guildmember.playerid"), primary_key=True)
name = Column(Unicode(45))
bases = dbsession.query(Base)
bases = bases.order_by(Base.owner.name)
这不起作用....我到处搜索并阅读文档。 但我只是不知道如何根据他们的'所有者'关系的名称对我的(基本)查询进行排序。
它总是导致:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name'
这一定很容易......但是我没有看到它。还查看了比较器,这似乎是合乎逻辑的,但我没有看到ORDER BY的查询部分在哪里生成或者我应该返回什么,因为所有内容都是动态生成的。为我的每个“玩家”关系制作一个比较器做一件简单的事情似乎过于复杂。
答案 0 :(得分:34)
SQLAlchemy希望您考虑SQL。如果您对“Base”进行查询,那就是:
SELECT * FROM base
容易。那么,在SQL中,你如何选择“base”中的行,并在一个完全不同的表中的“name”列中排序,即“player”?您使用联接:
SELECT base.* FROM base JOIN player ON base.ownerid=player.id ORDER BY player.name
SQLAlchemy让您使用相同的思维过程 - 您加入():
session.query(Base).join(Base.owner).order_by(Player.name)