如何基于一对一(三个表)创建一对多关系?

问题描述 投票:0回答:2

我正在使用flask和SQLachemy学习python上的后端开发。我已经理解了做一对一,一对多和多对多关系的方法。而现在我正试图做一个更棘手的关系。

有3个模型类,具有以下关系:

  • A类和B类具有一对一的关系
  • B类和C类有很多(B)到一(C)的关系
  • A类和C类有很多(C)到一(A)的关系

现在我想通过B关系创建C和A之间的关系(抽象问题的表述,继续阅读具体的公式)

文档谈到join,它可能是一种方法,但我无法理解示例https://docs.sqlalchemy.org/en/13/orm/join_conditions.html#composite-secondary-joins

from backend import db # db = SQLAlchemy(app)
class User(db.Model): # class A
    __tablename__ = 'User'
    id = db.Column(db.Integer, primary_key=True)
    # ...
    albums = db.relationship('Album', backref='auteur')
    # pictures taken as a photograph (pictures_posted may exist, but
    # that's still the same difficulty than with photographer, "circular"
    # relationships
    pictures_taken = db.relationship('Picture', backref='photographe')
class Picture(db.Model): # class B
    __tablename__ = 'Picture'
    id = db.Column(db.Integer, primary_key=True)
    # ...
    album_id = db.Column(db.Integer, db.ForeignKey('Album.id'))
    photographe_id = db.Column(db.Integer, db.ForeignKey('User.id'))
class Album(db.Model): # class C
    __tablename__ = 'Album'
    id = db.Column(db.Integer, primary_key=True)
    # ...
    pictures = db.relationship('Picture', backref='album')
    auteur_id = db.Column(db.Integer, db.ForeignKey('User.id'))

为了不那么抽象,我想直接从photographess实例访问album中代表的(全部)album。因为我可以访问auteurpictures

PS:我应该使用多态来处理问题(User的子类:Lambda; Photographe;作者)?

python sqlalchemy flask-sqlalchemy
2个回答
0
投票

如果您想要反向访问(从专辑到作者的所有图像):

album = Album.query.filter_by(id=111).first()

然后:

images = album.auteur.images

0
投票

实际上最方便的答案是在Album的类中使用一个属性。

class Album(db.Model):
    # ...
    @property
    def photographes(self):
        photographes = set()
        for img in self.pictures:
            if img.photographe not in photographes:
                photographes.add(img.photographe)
        return photographes

我在git上分享了我的后端,它可能很有用!

© www.soinside.com 2019 - 2024. All rights reserved.