I am getting this error: sqlalchemy.exc.ArgumentError: Mapper mapped class…
- User
I am getting this error: sqlalchemy.exc.ArgumentError: Mapper mapped class TempStockReturnDaily->temp_stock_return_daily could not assemble any primary key columns for mapped table 'temp_stock_return_daily'
when I try to work with the TempStockReturnDaily model from the script below. What changes do I need make to the script so I can work with the TempStockReturnDaily model without creating a primary key for it?
class AbstractBase: abstract = True
@declared_attr def __tablename__(cls): return to_underscored(cls.__name__) @classmethod def _generate_index(cls, is_unique, *columns, index_name=None): prefix = 'ux' if is_unique else 'ix' index_name = index_name or f'{prefix}_{cls.__tablename__}__{"__".join(columns)}' return Index(index_name, *columns, unique=is_unique)naming_convention = { "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" }
def get_Base(schema_name=None): kwargs = {} if schema_name: kwargs['schema'] = schema_name meta = MetaData(naming_convention=naming_convention, **kwargs) return declarative_base(cls=AbstractBase, metadata=meta)
class TemporaryModel(BaseTemp): prefixes = ['Temporary']
class TempStockReturnDaily(TemporaryModel): stock_series_id = Column(Integer, nullable=False) start_date = Column(Date(), nullable=False) end_date = Column(Date(), nullable=False) return_value = Column(Numeric(precision=18, scale=10), nullable=False)
- Assistant
The error is occurring because SQLAlchemy requires a primary key column in order to create a mapped table. To work with the
TempStockReturnDailymodel without creating a primary key, you can use SQLAlchemy'smutable=Trueoption to specify that the model is not backed by a table.Here's an updated version of the script that includes the necessary changes:
from sqlalchemy import Column, Integer, Date, Numeric from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import declarative_base Base = declarative_base() class TemporaryModel(Base): prefixes = ['Temporary'] class TempStockReturnDaily(TemporaryModel): __table_args__ = {'mutable': True} stock_series_id = Column(Integer, nullable=False) start_date = Column(Date(), nullable=False) end_date = Column(Date(), nullable=False) return_value = Column(Numeric(precision=18, scale=10), nullable=False)With these changes, the
TempStockReturnDailymodel will not have a primary key and will not be backed by a table. This allows you to work with the model without encountering theArgumentErrorrelated to the missing primary key.