I am new to SQLAlchemy. Trying to build database in Heroku Postgres
Get error: ArgumentError: Mapper mapped class Users->users could not assemble any primary key columns for mapped table 'users'
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, Integer, BigInteger, String, Sequence, TIMESTAMP, Boolean, JSON)
from sqlalchemy import sql
from sqlalchemy import Table, Column, Integer, String, MetaData, Sequence, create_engine
class Users(Base):
__tablename__ = 'users'
meta = MetaData()
users_table = Table(
'users', meta,
Column('id', Integer, primary_key=True),
Column('name',String(50)),
Column('fullname',String(50)),
Column('phone',Integer),
)
meta.create_all(engine)
def __repr__(self):
return "<User(id='{}', fullname='{}', username='{}')>".format(
self.id, self.full_name, self.username)
The main reasons this does not work is that you try to create the table before the class User
is created AND also the table you declare is not declared on the correct attribute. So sqlalchemy cannot find the id column. I have tried to outline a more idiomatic declarative approach below:
# This implicitly creates metadata, you do not need to make an explicit one.
Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
# Using a table explicitly is not required here
# Just declare the columns as properties.
id = Column(Integer, primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
phone = Column(Integer)
# Don't do this here because Users is not done
# meta.create_all(engine)
def __repr__(self):
return "<User(id='{}', fullname='{}', username='{}')>".format(
self.id, self.full_name, self.username)
# Do this after classes are declared and use Base's metadata.
Base.metadata.create_all(engine)
References:
If you really want to set a table you have to set it with __table__
and use Base.metadata
: https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html#using-a-hybrid-approach-with-table
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments