SQLAlchemy one to many relationship, how to filter the collection

时光怂恿深爱的人放手 提交于 2019-12-04 16:49:36

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 the primaryjoin argument, with an example that perfectly illustrating your required scenario. Adapting that with your requirements, the Product class now follows:

class Product(Base):

    __tablename__ = 'products'

    product_id = Column(Integer, primary_key=True)
    product_name = Column(String(100))
    product_pictures = relationship("ProductPicture")

    main_pictures = relationship("ProductPicture",
        primaryjoin="and_(Product.product_id==ProductPicture.product_id, "
                    "ProductPicture.picture_type=='main')")
    option_pictures = relationship("ProductPicture",
        primaryjoin="and_(Product.product_id==ProductPicture.product_id, "
                    "ProductPicture.picture_type=='option')")

Example session:

>>> p = Product()
>>> p.product_name = 'test product'
>>> p.product_id = 1
>>> session.add(p)
>>> pic1 = ProductPicture()
>>> pic1.product_id = p.product_id
>>> pic1.picture_type = 'main'
>>> pic1.url = 'http://example.com/p1.main.png'
>>> session.add(pic1)
>>> pic2 = ProductPicture()
>>> pic2.product_id = p.product_id
>>> pic2.picture_type = 'option'
>>> pic2.url = 'http://example.com/p1.option1.png'
>>> session.add(pic2)
>>> pic3 = ProductPicture()
>>> pic3.product_id = p.product_id
>>> pic3.picture_type = 'option'
>>> pic3.url = 'http://example.com/p1.option2.png'
>>> session.add(pic3)
>>> session.commit()
>>> [(pic.picture_type, pic.url) for pic in p.product_pictures]
[(u'main', u'http://example.com/p1.main.png'), (u'option', u'http://example.com/p1.option1.png'), (u'option', u'http://example.com/p1.option2.png')]
>>> [(pic.picture_type, pic.url) for pic in p.main_pictures]
[(u'main', u'http://example.com/p1.main.png')]
>>> [(pic.picture_type, pic.url) for pic in p.option_pictures]
[(u'option', u'http://example.com/p1.option1.png'), (u'option', u'http://example.com/p1.option2.png')]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!