Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy model inheritance without relations

I want to create two similar tables. I need not to create any realtions between them.

    class Table1(Base):
         __tablename__ = "table1"
         id = Column(UUIDType, primary_key=True, index=True, unique=True)
         value = Column(String(70), nullable=True)
    
     class Table2(Table1):
         __tablename__ = "table2"
         unit = Column(String(10), nullable=True)

But when I try to use that models I get

E   sqlalchemy.exc.NoForeignKeysError: Can't determine the inherit condition between inherited table 'table1' and inheriting table 'table2';

Is it possible to refuse automatic creation of the relations without abstract class usage?

like image 649
Alexander Vilnin Avatar asked Apr 26 '26 19:04

Alexander Vilnin


1 Answers

I'm not sure if by:

without abstract class usage

you meant avoiding abstract-concrete-classes, if so the solution that worked for me was using declarative_mixins, so in your case this would be:

class TableBase(object):
    id = Column(UUIDType, primary_key=True, index=True, unique=True)
    value = Column(String(70), nullable=True)

class Table1(TableBase, Base):
    __tablename__ = "table1"

class Table2(TableBase, Base):
    __tablename__ = "table2"
    unit = Column(String(10), nullable=True)
like image 88
Andy Avatar answered Apr 29 '26 08:04

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!