Use base class property / attribute as table column?

The game engine provides me with the Player class with the steamid property (coming from C ++, this is just a basic example of how it will look in Python):

 # game_engine.py class Player: def __init__(self, steamid): self.__steamid = steamid @property def steamid(self): return self.__steamid 

Then I will go to a subclass of this class by adding the gold attribute:

 # my_plugin.py class MyPlayer(game_engine.Player, Base): gold = Column(Integer) 

Now I need to save the gold player in the database with the steamid player as the primary key for identifying the player. How can I tell SQLAlchemy to use the steamid base class steamid as the primary key?

Here's something stupid I've tried:

 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property import game_engine Base = declarative_base() class Player(game_engine.Player, Base): __tablename__ = 'player' _steamid = game_engine.Player.steamid @hybrid_property def steamid(self): return type(self)._steamid.__get__(self) 

But yes, it was a long shot ...

 sqlalchemy.exc.ArgumentError: Mapper Mapper|Player|player could not assemble any primary key columns for mapped table 'player' 
+6
source share
2 answers

This is easier than you might expect. The solution below is roughly equivalent to the one from rmn, but more straight forward, since it uses modern declarative mapping. There is no need for @hybrid_property , you can just inherit steamid from the parent class.

 # my_plugin.py class MyPlayer(game_engine.Player, Base): def __init__(self, steamid, gold): super().__init__(steamid) self._id = self.steamid self.gold = gold _id = Column('steamid', Integer, primary_key=True) gold = Column(Integer) 
+2
source

this can be done using classic mapping

 from sqlalchemy import Column, Integer, Table from sqlalchemy.orm import mapper from sqlalchemy.ext.hybrid import hybrid_property class MyPlayer(Player): def __init__(self, steamid, gold): super().__init__(steamid) self.gold = gold self._steamid = super().steamid player = Table('player', Base.metadata, Column('_steamid', Integer, primary_key=True), Column('gold', Integer), ) mapper(MyPlayer, player) 
+1
source

All Articles