'How can i insert row into table sqlalchemy object?

i have table object that its name is tags and i don't know how to insert new row into it

this is my table object :

tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
    db.Column('Post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True)
)

i tried to use this query for test :

db.session.add(tags(
        post_id = 1,
        tag_id = 2
))

But I encountered this error :

TypeError: 'Table' object is not callable


Solution 1:[1]

An actual answer for the stated question, you need to get an Insert object from the table:

ins = tags.insert().values(post_id=1, tag_id=2)
db.engine.execute(ins)

Solution 2:[2]

I encourage you to use SQLAlchemy ORM approach. In your case it would be something like this:

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Tags(Base):
    __tablename__ = 'tags'

    tag_id = Column(Integer, ForeignKey('tags.id'), primary_key=True)
    post_id = Column(Integer, ForeignKey('posts.id'), primary_key=True)


session.add(Tags(tag_id=1, post_id=2))
session.commit()

Check SQLAlchemy site, they have great docs, recipes and examples!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maximilian Burszley
Solution 2