覆盖sqlalchemy

时间:2018-04-25 21:08:29

标签: python python-3.x sqlalchemy flask-sqlalchemy relationships

假设我以声明方式有三个表,ParentChildPet,以这种方式

  • ParentChildPet
  • 有多对多的关系
  • ChildPet
  • 有一对多的关系

它们的代码是(使用Flask-SQLAlchemy,虽然我相信解决方案存在于SQLAlchemy而不是Flask中)。

class Parent(db.Model):
    __tablename__ = 'parents'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))

    # many to many relationship between parent and children
    # my case allows for a children to have many parents. Don't ask.
    children = db.relationship('Child',
                           secondary=parents_children_relationship,
                           backref=db.backref('parents', lazy='dynamic'),
                           lazy='dynamic')

    # many to many relationship between parents and pets
    pets = db.relationship('Pet',
                             secondary=users_pets_relationship,
                             backref=db.backref('parents', lazy='dynamic'), #
                             lazy='dynamic')

# many to many relationship between parents and children
parents_children_relationship = db.Table('parents_children_relationship',
    db.Column('parent_id', db.Integer, db.ForeignKey('parents.id')),
    db.Column('child_id', db.Integer, db.ForeignKey('children.id')),
    UniqueConstraint('parent_id', 'child_id'))

# many to many relationship between User and Pet 
users_pets_relationship = db.Table('users_pets_relationship', 
    db.Column('parent_id', db.Integer, db.ForeignKey('parents.id')), 
    db.Column('pet_id', db.Integer, db.ForeignKey('pets.id')),
    UniqueConstraint('parent_id', 'pet_id'))

class Child(db.Model):
    __tablename__ = 'children'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    # parents = <backref relationship with User model>

    # one to many relationship with pets
    pets = db.relationship('Pet', backref='child', lazy='dynamic')


class Pet(db.Model):
    __tablename__ = 'pets'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    # child = backref relationship with cities
    child_id = db.Column(db.Integer, db.ForeignKey('children.id'), nullable=True)
    # parents = <relationship backref from User>

我想做这样的事情

parent_a = Parent()    
child_a = Child()
pet_a = Pet()

我可以这样做

parent_a.children.append(child_a)
# commit/persist data
parent_a.children.all() # [child_a]

我想实现这样的目标

child_a.pets.append(pet_a)
parent_a.children.append(child_a)
# commit/persist data
parent_a.children.all() # [child_a]
parent_a.pets.all() # [pet_a], because pet_a gets 
                    # automatically added to parent using some sorcery
                    # like for child in parent_a.children.all():
                    #     parent.pets.append(child.pets.all())
                    # or something like that.

我可以使用像Parent这样的add_child_and_its_pets()对象中的方法实现此目的,但我想覆盖关系的工作方式,因此我不需要覆盖其他可能的模块受益于此行为,例如Flask-Admin

基本上我应该如何覆盖backref.append方法或relationship.append方法,以便在呼叫时,即在python端附加来自其他关系的其他对象?我该如何覆盖remove方法?

2 个答案:

答案 0 :(得分:2)

对于parent.pets.all(),我认为您可以将子项视为secondary join条件,并将其视为associative entity or junction table

这取决于您的表格,但这看起来像是:

Parent.pets = relationship(
    Pet,
    backref='parent'
    primaryjoin=Pet.child_id == Child.id,
    secondaryjoin=Child.parent_id == Parent.id
)

如果你愿意,你也可以合理地制作一个backref parent - 这样你就可以同时访问parent_a.petspet_a.parent

答案 1 :(得分:2)

使用sqlalchemy mailing list中的相同答案,这可以使用event listeners来实现,https://wiki.qt.io/How_to_create_a_multi_language_application在第一个对象上调用appendremove之前调用参数。

@db.event.listens_for(Parent.children, 'append')
def _append_children(parent, child, initiator):
    # appends also the pets bound to the child that the 
    # is being appended to the Parent

    parent.pets.extend(child.pets.all())

    # at the end of this call, executes
    # parent.children.append(child)