I am trying to create a self referencing table in MySql using SqlAlchemy. I get the error
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'ForeignKey'
My code is
from sqlalchemy import (
create_engine,
Column,
Integer,
String,
DateTime,
func,
Text,
DECIMAL,
ForeignKey,
)
# from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, declarative_base, mapped_column, relationship
Base = declarative_base()
class Account(Base):
__tablename__ = "account"
id = mapped_column(Integer, primary_key=True)
name = mapped_column(String(50))
notes = mapped_column(Text())
opening_balance = DECIMAL()
current_balance = DECIMAL()
parent_id = mapped_column(Integer, ForeignKey="account.id") #error here
children = relationship("Account")
created_at = mapped_column(DateTime, default=func.now())
updated_at = mapped_column(DateTime, default=func.now(), onupdate=func.now())
The error occurs at the line parent_id = ...
Everywhere I looked suggested that the code is correct (and I've looked in a lot of places). Co-Pilot told me to put ()
around "account.id"
but PyCharm told me they were redundant. Either way got the error.
Tried changing mapped_column
to Column
, same error.
Haven't got a clue what to do!
I am trying to create a self referencing table in MySql using SqlAlchemy. I get the error
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'ForeignKey'
My code is
from sqlalchemy import (
create_engine,
Column,
Integer,
String,
DateTime,
func,
Text,
DECIMAL,
ForeignKey,
)
# from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, declarative_base, mapped_column, relationship
Base = declarative_base()
class Account(Base):
__tablename__ = "account"
id = mapped_column(Integer, primary_key=True)
name = mapped_column(String(50))
notes = mapped_column(Text())
opening_balance = DECIMAL()
current_balance = DECIMAL()
parent_id = mapped_column(Integer, ForeignKey="account.id") #error here
children = relationship("Account")
created_at = mapped_column(DateTime, default=func.now())
updated_at = mapped_column(DateTime, default=func.now(), onupdate=func.now())
The error occurs at the line parent_id = ...
Everywhere I looked suggested that the code is correct (and I've looked in a lot of places). Co-Pilot told me to put ()
around "account.id"
but PyCharm told me they were redundant. Either way got the error.
Tried changing mapped_column
to Column
, same error.
Haven't got a clue what to do!
1 Answer
Reset to default 0ForeignKey
is a function so the (...)
need to be instead of the =
, your line needs to be:
parent_id = mapped_column(Integer, ForeignKey("account.id"))