Flask/SQLAlchemy - Add record to parent and association table without add record to child in many-many relationchip?

Viewed 86

we have two models (User, Role) with tables name (ab_user, ab_role) many to many relationship with association table assoc_user_role (ab_user_role) I need to add records to ab_user table and assoc_user_role association table without adding to ab_role table.

assoc_user_role = Table(
    "ab_user_role",
    Model.metadata,
    Column("id", Integer, Sequence("ab_user_role_id_seq"), primary_key=True),
    Column("user_id", Integer, ForeignKey("ab_user.id")),
    Column("role_id", Integer, ForeignKey("ab_role.id")),
    UniqueConstraint("user_id", "role_id"),
)

class Role(Model):
    __tablename__ = "ab_role"

    id = Column(Integer, Sequence("ab_role_id_seq"), primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    permissions = relationship(
        "PermissionView", secondary=assoc_permissionview_role, backref="role"
    )

    def __repr__(self):
        return self.name

class User(Model):
    __tablename__ = "ab_user"
    id = Column(Integer, Sequence("ab_user_id_seq"), primary_key=True)
    first_name = Column(String(64), nullable=False)
    last_name = Column(String(64), nullable=False)
    username = Column(String(64), unique=True, nullable=False)
    password = Column(String(256))
    active = Column(Boolean)
    email = Column(String(64), unique=True, nullable=False)
    roles = relationship("Role", secondary=assoc_user_role, backref="user")

Can someone show me how to do the following?

when we have ab_role table with data and need to add a new user to the ab_user table with using one of the existing roles in the ab_role table and in same time add record to ab_user_role (association table) to link between new user and role from ab_role table.

Thanks in advance.

0 Answers
Related