简体   繁体   中英

How to insert many to many record data?

Please consider the following use case.

There is a Post model as well as a Tag model. Both of them have a many-to-many relationship between them. A post can have multiple tags while a tag can have multiple posts .

In order to attain this use case, I have implemented a mapping table called, PostTag and it looks like as follows

from database.base import Base
from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.orm import relationship
from .model_post import ModelPost
from .model_tag import ModelTag


class PostTag(Base):
   __tablename__ = 'posttag'
   post_id = Column("post_id",Integer, ForeignKey('post.id'), primary_key = True)
   tag_id = Column("tag_id",Integer, ForeignKey('tag.id'), primary_key = True)

With this setup, I can successfully query all the tags for a given post and vice versa, but I dont know to add a new association for a given post and tag .

Please see the below screenshot on how I query the related tags and posts off of each other.

在此处输入图片说明

If there is anything that I am missing here, please let me know.

Thanks

I peeped into some my old code, setup models like this:

from sqlalchemy.orm import sessionmaker

posttag = Table(
    "posttag",
    Base.metadata,
    Column("id", INTEGER, Sequence("seq_posttag_id"), primary_key=True),
    Column("post_id", INTEGER, ForeignKey("post.id")),
    Column("tag_id", INTEGER, ForeignKey("tag.id")),
)


class ModelTag(Base):
    __tablename__ = "tag"

    id = Column(INTEGER, Sequence("seq_tag_id"), primary_key=True)
    name = Column(VARCHAR(40), nullable=False)


class ModelPost(Base):
    __tablename__ = "post"

    id = Column(INTEGER, Sequence("seq_post_id"), primary_key=True)
    name = Column(VARCHAR(100), nullable=False)
    tags = relationship(Tag, secondary=posttag)

And so when you create a new Post, then you add a tag to it without directly referencing posttag table:

post = Post(name="foo")

tag = session.query(ModelTag).filter_by(name='some').first()
post.append(tag)

session = Session()
session.add(post)
session.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM