SQLAlchemy Many-To-Many join SQLAlchemy Many-To-Many join flask flask

SQLAlchemy Many-To-Many join


First, in your products table, your second foreign key needs to property reference the table name "tags", so change 'tag.id' to 'tags.id'

products_tags_table=db.Table('products_tags',                    db.Column('product_id', db.Integer,db.ForeignKey('products.id'), nullable=False),                    db.Column('tag_id',db.Integer,db.ForeignKey('tags.id'),nullable=False),                                                                    #^Missing 's'                    db.PrimaryKeyConstraint('product_id', 'tag_id')                    )

And then in your products model, you want to accurately reference the name of the appropriate model. Change 'ProductTag' to 'Tag'

tags=db.relationship('Tag', # 'ProductTag' <- This is a relationship to the Tag table.                    secondary=products_tags_table,                    backref='tag_products'                    )  

Then try your join like this

query = Tag.query.join(Product, Tag.products)avail_tags = query.order_by(Tag.name).all()