多态一对多关系,其中"很多"属于不同的子类

时间:2017-01-25 08:14:51

标签: python python-3.x sqlalchemy relationship

我有一个Player课程,每个玩家拥有X个Character个实例:

class Player(Model):
    characters = relationship('Character', back_populates='owner')

class Character(Model):
    owner = relationship('Player', back_populates='characters')
    owner_id = Column('player_id', Integer, ForeignKey('player.id'))
    level = Column(Integer, default=0)

但是现在我想让Character成为__abstract__的基类,并且只记录它的子类'实例进入数据库:

class Character(Model):
    __abstract__ = True
    owner = relationship('Player', back_populates='characters')
    owner_id = Column('player_id', Integer, ForeignKey('player.id'))
    level = Column(Integer, default=0)

    def use_special_ability(self, target):
        raise NotImplementedError

class Warrior(Character):
    def use_special_ability(self, target):
        bla_bla(target)

class Mage(Character):
    def use_special_ability(self, target):
        foo(self.level, bar=True)

对我来说,只有一个character表或者所有字符子类是否都有自己的表(尽管前者稍微偏好)对我来说并不重要,只要Python方面工作"完美无瑕",即每个玩家都有一个字符列表,无论其类型如何。

我如何更改关系,以便它适用于多个这样的子类?

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

class Player(Model):
    __tablename__ = "player"

    characters = relationship('Character', back_populates='owner')


class Character(Model):
    __tablename__ = "character"

    id = Column(Integer, primary_key=True)
    type = Column(Enum("warrior", "mage")), nullable=False)
    owner = relationship('Player', back_populates='characters')
    owner_id = Column('player_id', Integer, ForeignKey('player.id'))

    __mapper_args__ = {
        "polymorphic_on": type,
    }

    ...


class Warrior(Character):
    __tablename__ = None

    __mapper_args__ = {
        "polymorphic_identity": "warrior",
    }

    ...


class Mage(Character):
    __tablename__ = None

    __mapper_args__ = {
        "polymorphic_identity": "mage",
    }

    ...