Bacially Product
has a one to many relationship to ProductPicture
.
My product picture model looks like this:
picture_type_enums = ('main', 'related', 'option')
class ProductPicture(Base):
__tablename__ = 'product_pictures'
picture_id = Column(Integer, primary_key = True)
product_id = Column(Integer, ForeignKey('products.product_id'))
picture_type = Column(Enum(*picture_type_enums))
url = Column(String(120))
and my product model looks like this:
class Product(Base):
__tablename__ = 'products'
product_id = Column(Integer, primary_key=True)
product_name = Column(String(100))
product_pictures = relationship("ProductPicture")
My question is for one product I might have different types of product pictures. I know if I have a Product
instance p
, I can call p.product_pictures
to get all types of product pictures. However, I want something like p.main_pictures
which get all the product pictures of type 'main'
, and p.option_pictures
gets all the product_pictures
of type 'option'
. Is there a good way to do it.
Thanks
If you read the documentation for
sqlalchemy.orm.relationship
, you can see that you can further limit the relationship by explicitly define the condition using theprimaryjoin
argument, with an example that perfectly illustrating your required scenario. Adapting that with your requirements, theProduct
class now follows:Example session: