[英]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. 有一个
Post
模型和一个Tag
模型。 Both of them have a many-to-many
relationship between them. 它们两者之间
many-to-many
关系。 A post
can have multiple tags
while a tag
can have multiple posts
. 一个
post
可以有多个tags
而一个tag
可以有多个posts
。
In order to attain this use case, I have implemented a mapping table called, PostTag
and it looks like as follows 为了达到这个用例,我实现了一个名为
PostTag
的映射表,它看起来如下
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
. 通过这种设置,我可以成功查询给定
post
所有tags
,反之亦然,但是我不知道为给定post
和tag
添加新的关联。
Please see the below screenshot on how I query the related tags
and posts
off of each other. 请查看以下屏幕截图,了解我如何查询相关
tags
和彼此之间的posts
。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.