I’ve seen many solutions, but I still can’t get this to work. I have
class ModuleGroupMember(ModelBase):
__tablename__ = 'module_group_member'
pk = mapped_column(Integer, primary_key=True)
module_pk = mapped_column(Integer, ForeignKey('module.pk'))
module_group_pk = mapped_column(Integer, ForeignKey('module_group.pk'))
class Module(ModelBase):
__tablename__ = 'module'
pk = mapped_column(Integer, primary_key=True)
name = mapped_column(String)
groups = relationship("Module_Group", secondary="module_group_member", back_populates="modules")
class ModuleGroup(ModelBase):
__tablename__ = 'module_group'
pk = mapped_column(Integer, primary_key=True)
description = mapped_column(String)
is_active = mapped_column(Boolean)
name = mapped_column(String)
modules = relationship("Module", secondary="module_group_member", back_populates="groups")
It’s not clear to me if the secondary
parameter is the table name or class name, but I’ve tried both.
When I try to create the tables, the Assocation table is not created.
If I then try to do an insert into the Module table with
session.add(Module(name="Module1"))
session.commit()
I get an error sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper[Module(module)], expression 'module_group_member' failed to locate a name ("name 'module_group_member' is not defined"). If this is a class name, consider adding this relationship() to the <class 'root.db.models.Module.Module'> class after both dependent classes have been defined.
I’m assuming the error is caused by the fact that the table was not created. I have all my table definitions in a separate file. Not sure if it has to do with the order of the loading or something like that