我有两个表Items和ItemDescriptions
class Item(Base):
__tablename__ = "item"
id = Column(Integer, primary_key=True)
description_id = Column(Integer, ForeignKey('item_description.id'))
class ItemDescription(Base):
__tablename__ = "item_description"
id = Column(Integer, primary_key=True)
鉴于ItemDescriptions列表,我想要一个Items列表,以便每个ItemDescription id都有一个项目。我不关心哪个项目。
[为清晰起见而编辑]
给出这个项目和描述清单:
Item, Description
1 , 1
2 , 1
3 , 1
4 , 2
5 , 2
6 , 3
7 , 3
8 , 3
我想要一个返回类似的查询:
Item, Description
2 , 1
4 , 2
7 , 3
我在处理子查询等方面遇到了麻烦。
感谢您的帮助
答案 0 :(得分:2)
我是column_property的忠实粉丝。以下是使用column_property执行所需操作的方法:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Item(Base):
__tablename__ = 'item'
id = Column(Integer, primary_key=True)
description_id = Column(Integer, ForeignKey('item_description.id'))
class ItemDescription(Base):
__tablename__ = 'item_description'
id = Column(Integer, primary_key=True)
any_item_id = column_property(
select(
[Item.id],
id == Item.description_id,
limit=1,
).label('any_item_id'),
deferred=True,
)
e = create_engine('sqlite://', echo=True)
Base.metadata.create_all(e)
s = Session(e)
descriptions = [
ItemDescription(id=1),
ItemDescription(id=2),
ItemDescription(id=3),
]
s.add_all(descriptions)
items = [
Item(id=1, description_id=1),
Item(id=2, description_id=1),
Item(id=3, description_id=1),
Item(id=4, description_id=2),
Item(id=5, description_id=2),
Item(id=6, description_id=3),
Item(id=7, description_id=3),
Item(id=8, description_id=3),
]
s.add_all(items)
query = s.query(ItemDescription).options(undefer('any_item_id'))
for description in query:
print description.any_item_id, description.id
# alternative way without using column_property
query = s.query(
select(
[Item.id],
ItemDescription.id == Item.description_id,
limit=1,
).label('any_item_id'),
ItemDescription,
)
for item_id, description in query:
print item_id, description.id
答案 1 :(得分:0)
from sqlalchemy.orm import relationship, backref
class Item(Base):
__tablename__ = "item"
id = Column(Integer, primary_key=True)
description_id = Column(Integer, ForeignKey('item_description.id'))
desc = relationship(User, backref=backref('desc', order_by=id))
class ItemDescription(Base):
__tablename__ = "item_description"
id = Column(Integer, primary_key=True)
Now your every ItemDescription class will have an backref called `desc` which is nothing but a list of Item.
Now you can do something like this
item_desc = session.query(ItemDescription).\
... options(joinedload('desc').all()
for item in item_desc:
print item.desc
我认为这可能不会给你确切的答案。它会帮助我猜测