Issue using declarative base and single table inheritance

Issue #3686 invalid
Bastien Gérard created an issue

Hi there, I'm trying to use a declarative_base and single table inheritance together but it throws : * sqlalchemy.exc.InvalidRequestError: Table 'persons' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.*

Example below:

from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

class CustomBase(object):
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    __table_args__ = {'mysql_engine': 'InnoDB'}


Base = declarative_base(cls=CustomBase)

class Person(Base):
    __tablename__ = 'persons'

    id =  Column(Integer, primary_key=True)
    type = Column(String(50), nullable=False)

    __mapper_args__ = {'polymorphic_on': type}


class Manager(Person):
    __mapper_args__ = {'polymorphic_identity': 'manager'}
    name = Column(String(50), nullable=False)

I noticed that commenting the following lines in the CustomBase "solves" the problem.

#    @declared_attr
#    def __tablename__(cls):
#        return cls.__name__.lower()

Thanks!

Comments (2)

  1. Bastien Gérard reporter

    my bad, indeed adding

    __tablename__ = None
    

    explicitly in the Manager class did the trick. Thanks for the quick feedback

  2. Log in to comment