我有两张已经填充的表格,
class Shelter(Base):
__tablename__ = 'shelter'
id = Column(Integer, primary_key = True)
name = Column(String(80), nullable = False)
address = Column(String(250))
city = Column(String(80))
state = Column(String(20))
zipCode = Column(String(10))
website = Column(String)
class Puppy(Base):
__tablename__ = 'puppy'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
gender = Column(String(6), nullable = False)
dateOfBirth = Column(Date)
picture = Column(String)
shelter_id = Column(Integer, ForeignKey('shelter.id'))
shelter = relationship(Shelter)
weight = Column(Numeric(10))
现在,我想编写一个查询,使用Python通过他们的Shelter名称获取所有Puppies组。因此,它需要打印为puppyName puppyShelterName
。
我按如下方式编写代码,
puppies = session.query(Puppy).group_by(Puppy.shelter_id).all()
for puppy in puppies:
puppy.name
这显然不能按我的意愿行事。我想在他们住的避难所中打印所有小狗的名字和他们的避难所名称组。如何更正代码?
答案 0 :(得分:2)
从提供的附加信息来看,似乎ORDER BY
就足够了。这些模型还需要加入,以便打印出小狗的名字和庇护所的名称:
results = session.query(Puppy.name, Shelter.name)\
.join(Shelter).order_by(Shelter.name, Puppy.name).all()
for puppy, shelter in results:
print(puppy, shelter) # or `print puppy, shelter` if on PY2
如果你的关系中有背景,你也可以采取不同的做法:
class Puppy(Base):
...
shelter = relationship(Shelter, backref='puppies')
然后你可以先选择所有的避难所,然后使用backref迭代小狗。根据backref配置的急切程度,这可以发出单个查询,也可以选择所有Shelter
和select for shel shelter来获取Puppy
个实例。
from sqlalchemy.orm import joinedload
shelters = session.query(Shelter).options(joinedload('puppies')).all()
for shelter in shelters:
for puppy in shelter.puppies:
print(puppy.name, shelter.name)