Python 如何在SQLAlchemy中存储和搜索列表?
我需要写两个这样的类:Python 如何在SQLAlchemy中存储和搜索列表?,python,sqlalchemy,pyramid,Python,Sqlalchemy,Pyramid,我需要写两个这样的类: class Item(Base, DBBase): __tablename__ = 'items' id = Column(Integer, primary_key = True) name = Column(String) description = Column(String) price = Column(Float, default = 0) on_sell = Column(Boolean, default =
class Item(Base, DBBase):
__tablename__ = 'items'
id = Column(Integer, primary_key = True)
name = Column(String)
description = Column(String)
price = Column(Float, default = 0)
on_sell = Column(Boolean, default = False)
img = Column(String)
attributes = relationship('ItemAttribute')
def __init__(self, name, description):
self.name = name
self.description = description
class ItemAttribute(Base, DBBase):
__tablename__ = 'itemattributes'
id = Column(Integer, primary_key = True)
name = Column(String, nullable = False)
value = Column(String, nullable = False)
item_id = Column(Integer, ForeignKey('items.id'))
item = relationship('Item')
def __init__(self, name, value):
self.name = name
self.value = value
一个项目可以拥有多个属性,我需要:
1.在类项上插入一些方法,以便对其执行CURD(插入、删除、更新和查询)属性。我需要搜索一个项目的属性并返回它对应的值。
2.能够按属性搜索项目。例如,某些项的属性为“Feature”=“True”。我需要获取所有具有此属性的项目
谢谢你的帮助。:-) 如果将backref添加到ItemAttribute关系中:
item_id = Column(Integer, ForeignKey('items.id', onupdate='CASCADE', ondelete='CASCADE'))
item = relationship(Items, backref='attributes')
这将创建和Item.attributes[]数组,其中包含ItemAttribute的。如果使用mysql,还可以添加onupdate和ondelete
然后在查询时,可以执行以下操作:
rs = mySession.query(Items)
firstItem = rs.first()
for attribute in firstItem.attributes:
print attribute
查询时,您可以通过加入backref进行筛选:
rs = mySession.query(Items).join(Items.attributes).filter(ItemAttribute.name=='somethingSpecial')
此外,如果是一对一关系(但本例中不是),可以通过指定uselist=False跳过该列表:
item = relationship(ITEM, backref='attribute', uselist=False)
谢谢你的帮助!顺便说一句:我很少使用'backref'参数,因为它在类定义文件中添加了一些东西,而没有任何提示,这使得类具有一些'hidden'属性。是的,这也让我很恼火。我通常会在类中添加一个带有注释的伪变量,比如:
attributes=None#:ItemAttribute backref的伪占位符
——它会被很好地覆盖,但至少是为了您的理智和任何代码检查器。