How to create an interface table in sqlAlchemy (relation many-to-many)

126 Views Asked by At

I'm using SqlAlchemy to interact with an existing Mariadb database. I need to access data organized in a many-to-many relationship. According to the source site documentation (sqlAlchemy), I created a multi-to-multiple relationship, but after entering the flask db migrate command, I get an error.

It should be noted that the tables of posts and categories have been created.

Documents for creating the interface table:


from sqlalchemy import Column, String, Text, Integer, Table, ForeignKey
from app import db


posts_categories = Table('posts_categories', db.metadata,
    Column('post_id', Integer, ForeignKey('posts.id', ondelete='cascade')),
    Column('category_id', Integer, ForeignKey('categories.id', ondelete='cascade'))
)

class Category(db.Model):
    __tablename = 'categories'
    id = Column(Integer, primary_key=True)
    name = Column(String(128), nullable=False, unique=True)
    description = Column(String(256), nullable=True, unique=False)
    slug = Column(String(128), nullable=False, unique=True)
    posts = db.relationship('Post', secondary=posts_categories, back_populates='categories')


class Post(db.Model):
    __tablename = 'posts'
    id = Column(Integer, primary_key=True)
    title = Column(String(128), nullable=False, unique=True)
    summary = Column(String(256), nullable=True, unique=False)
    content = Column(Text, nullable=False, unique=False)
    slug = Column(String(128), nullable=False, unique=True)
    categories = db.relationship('Category', secondary=posts_categories, back_populates='posts')
0

There are 0 best solutions below