Flask/SQLAlchemy How can I correct field when creating table with reflect?

I want to use metadata.reflect() and generate the existing tables. Tried Method 1 and Method 2 in code block to generate the table. They both give the same error about the Mapper not being able to assemble any primary key columns for mapped table. I think it’s because of the <built-in function id> field. How can I solve mapping issue?

What I’ve done:

  1. Read the package docs’ tutorial: https://flask-sqlalchemy.palletsprojects.com/en/3.1.x/models/
  2. I’ve checked the few other similar questions to this:
  • getting sqlalchemy view reflection to work in flask-sqlalchemy
  • how to reflect an existing table by using flask_sqlalchemy
  1. Asked ChatGPT

One suggested solution for the <built-in function id> is to declare a primary key, but I thought my original CREATE TABLE statement does that. Does it not? I’ve tried using __mapper_args__ on my own, but can’t figure out how to assign the shelf_id or id (I’ve tried both). The ultimate workaround seems to be to write out every table column, but the database isn’t finalized yet, so…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>engine = create_engine(AppConfig.DBURI, echo=False)
meta = MetaData()
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
def init_db(engine):
meta.init_db()
meta.create_all(bind=engine)
Base = declarative_base()
Base.metadata.reflect(bind=engine)
# Method 1
class Bookshelf(Base):
__table__ = Table("bookshelf",
Base.metadata,
Column('shelf_id', Integer),
autoload_with=engine,
extend_existing=True)
# Method 2
# class Bookshelf(Base):
# __table__ = Base.metadata.tables['bookshelf']
if __name__ == '__main__':
for table in Base.metadata.tables.values():
logging.debug(f"{table.name}")
for column in table.c:
logging.debug(f"{column.name}")
</code>
<code>engine = create_engine(AppConfig.DBURI, echo=False) meta = MetaData() db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) def init_db(engine): meta.init_db() meta.create_all(bind=engine) Base = declarative_base() Base.metadata.reflect(bind=engine) # Method 1 class Bookshelf(Base): __table__ = Table("bookshelf", Base.metadata, Column('shelf_id', Integer), autoload_with=engine, extend_existing=True) # Method 2 # class Bookshelf(Base): # __table__ = Base.metadata.tables['bookshelf'] if __name__ == '__main__': for table in Base.metadata.tables.values(): logging.debug(f"{table.name}") for column in table.c: logging.debug(f"{column.name}") </code>
engine = create_engine(AppConfig.DBURI, echo=False)
meta = MetaData()
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
def init_db(engine):
    meta.init_db()
    meta.create_all(bind=engine)

Base = declarative_base()
Base.metadata.reflect(bind=engine)

# Method 1
class Bookshelf(Base):
    __table__ = Table("bookshelf",
                      Base.metadata,
                      Column('shelf_id', Integer),
                      autoload_with=engine,
                      extend_existing=True)

# Method 2
# class Bookshelf(Base):
#    __table__ = Base.metadata.tables['bookshelf']

if __name__ == '__main__':
    for table in Base.metadata.tables.values():
        logging.debug(f"{table.name}")
        for column in table.c:
            logging.debug(f"{column.name}")

Errors:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>raise sa_exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Mapper Mapper[Bookshelf(bookshelf)] could not assemble any primary key columns for mapped table 'bookshelf'
</code>
<code>raise sa_exc.ArgumentError( sqlalchemy.exc.ArgumentError: Mapper Mapper[Bookshelf(bookshelf)] could not assemble any primary key columns for mapped table 'bookshelf' </code>
raise sa_exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Mapper Mapper[Bookshelf(bookshelf)] could not assemble any primary key columns for mapped table 'bookshelf'

If I run the same code above without the Table class, I get:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>2024-05-31 11:42:23,355 [DEBUG] bookshelf.<module>, line 67: bookshelf
2024-05-31 11:42:23,356 [DEBUG] bookshelf.<module>, line 69: <built-in function id>
2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: shelf_label
2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: directory_name
2024-05-31 11:42:23,358 [DEBUG] bookshelf.<module>, line 69: url
</code>
<code>2024-05-31 11:42:23,355 [DEBUG] bookshelf.<module>, line 67: bookshelf 2024-05-31 11:42:23,356 [DEBUG] bookshelf.<module>, line 69: <built-in function id> 2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: shelf_label 2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: directory_name 2024-05-31 11:42:23,358 [DEBUG] bookshelf.<module>, line 69: url </code>
2024-05-31 11:42:23,355 [DEBUG] bookshelf.<module>, line 67: bookshelf
2024-05-31 11:42:23,356 [DEBUG] bookshelf.<module>, line 69: <built-in function id>
2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: shelf_label
2024-05-31 11:42:23,357 [DEBUG] bookshelf.<module>, line 69: directory_name
2024-05-31 11:42:23,358 [DEBUG] bookshelf.<module>, line 69: url

The table was created separately by database_admin.py.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> CREATE TABLE IF NOT EXISTS bookshelf(
shelf_id INTEGER UNIQUE NOT NULL,
shelf_label TEXT UNIQUE NOT NULL ,
directory_name TEXT NOT NULL,
url TEXT NOT NULL,
creation_date DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_date DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (shelf_id),
UNIQUE(shelf_label, directory_name)
);
</code>
<code> CREATE TABLE IF NOT EXISTS bookshelf( shelf_id INTEGER UNIQUE NOT NULL, shelf_label TEXT UNIQUE NOT NULL , directory_name TEXT NOT NULL, url TEXT NOT NULL, creation_date DATETIME DEFAULT CURRENT_TIMESTAMP, updated_date DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (shelf_id), UNIQUE(shelf_label, directory_name) ); </code>
            CREATE TABLE IF NOT EXISTS bookshelf(
                shelf_id INTEGER UNIQUE NOT NULL,
                shelf_label TEXT UNIQUE NOT NULL ,
                directory_name TEXT NOT NULL,
                url TEXT NOT NULL,
                creation_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (shelf_id),
                UNIQUE(shelf_label, directory_name)
            );

Also tried it with shelf_id INTEGER PRIMARY KEY UNIQUE NOT NULL JIC.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật