I need to write two classes like this:
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
One item can own several attributes, and I need to:
1. insert some methods on class Item to easily do CURD(insertion, deletion, update and query) attributes for it. I need to search a attribute of a item and return it’s corresponding value.
2. have the ability to search items by attributes. For example, some items have the attributes of ‘Feature’ = ‘True’. I need to get all items which have this attribute.
Thanks for help. 🙂
If you add backref onto your ItemAttribute relationship:
This will create and Item.attributes[] array which contains the ItemAttribute’s. You might also add the onupdate and ondelete if you’re using mysql.
Then when you query, you can do this:
When querying you can filter by joining the backref:
Further, if it’s a one to one relationship (but it’s not in this case), you could skip the list by specifing uselist=False: