TypeError when autoincrementing column in sqlalchemy
Question:
I have the following table definition
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(String(256), unique=True)
is_admin = Column(Boolean, nullable=False)
def __init__(self, id, email, is_admin):
self.id = id
self.email = email
self.is_admin = is_admin
When I add a user I only call it with two arguments because I would like the id to be autoincremented and hence not passed by my call:
u = User(email=email, is_admin=admin)
but I get the following error:
TypeError: __init__() missing 1 required positional argument
How do I define a primary_key column without the need to pass it as an argument?
Answers:
You do not need this __init__
definition, inheriting from Base
creates one for you, which accepts only keyword arguments, not positional which is causing the issue with missing id
in your question.
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(String(256), unique=True)
is_admin = Column(Boolean, nullable=False)
u = User(email=email, is_admin=admin) # OK
I have the following table definition
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(String(256), unique=True)
is_admin = Column(Boolean, nullable=False)
def __init__(self, id, email, is_admin):
self.id = id
self.email = email
self.is_admin = is_admin
When I add a user I only call it with two arguments because I would like the id to be autoincremented and hence not passed by my call:
u = User(email=email, is_admin=admin)
but I get the following error:
TypeError: __init__() missing 1 required positional argument
How do I define a primary_key column without the need to pass it as an argument?
You do not need this __init__
definition, inheriting from Base
creates one for you, which accepts only keyword arguments, not positional which is causing the issue with missing id
in your question.
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
email = Column(String(256), unique=True)
is_admin = Column(Boolean, nullable=False)
u = User(email=email, is_admin=admin) # OK