Flask-SQLAlchemy 多对多插入

Posted

技术标签:

【中文标题】Flask-SQLAlchemy 多对多插入【英文标题】:Flask-SQLAlchemy Many to Many Insert 【发布时间】:2017-05-04 04:01:05 【问题描述】:

Flask sqlalchemy many-to-many insert data

我已尝试上述建议,但在插入带有标签的新帖子时,在附加多对多属性时继续收到以下错误。

任何方向都将不胜感激!

下午 1:06:22 web.1 | post.tags.append(post_tag)

11:06:22 PM web.1 |附加文件“/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/collections.py”,第 1072 行

11:06:22 PM web.1 | item = __set(self, item, _sa_initiator)

11:06:22 PM web.1 | __set 中的文件“/home/trevor/Projects/trevorblog/venv/local /lib/python2.7/site-packages/sqlalchemy/orm/collections.py”,第 1044 行

11:06:22 PM web.1 | item = executor.fire_append_event(item, _sa_initiator)

11:06:22 PM web.1 | fire_append_event 中的文件“/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/collections.py”,第 716 行

11:06:22 PM web.1 |项目,发起者)

11:06:22 PM web.1 | fire_append_event 中的文件“/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py”,第 936 行

11:06:22 PM web.1 |发起者或 self._append_token 或 self._init_append_token())

11:06:22 PM web.1 |文件“/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py”,第 1171 行,在 emit_backref_from_collection_append_event 中

11:06:22 PM web.1 | child_state, child_dict = instance_state(child), \

11:06:22 PM web.1 | AttributeError:“BaseQuery”对象没有属性“_sa_instance_state”

模型.py

blog_tag = db.Table('post_tag',
db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)

class Post(db.Model):
    """SQLAlchemy Post object class"""
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    timestamp = db.Column(db.DateTime)    
    title = db.Column(db.String(50))
    author = db.Column(db.Integer, db.ForeignKey('user.id'))
    uuid = db.Column(db.String(255))
    tags = db.relationship('Tag',secondary=blog_tag, 
                        back_populates="posts")

class Tag(db.Model):
    """SQLAlchemy Tag object class"""
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String, unique=True, nullable=False)
    posts = db.relationship('Post', secondary = blog_tag,
                            back_populates = "tags")

Views.py

@console.route('/new_post', methods=['GET', 'POST'])
@login_required
def new_post():
    post_form = PostForm()
    if post_form.validate_on_submit():
        """Take the list of tags and turn them into an array"""
       uid = uuid.uuid4()
       post = Post()
       post.title = post_form.title.data
       post.body = post_form.body.data
       post.timestamp = datetime.utcnow()
       post.author = current_user.id
       post.uuid = uid.hex
       tag_string = post_form.tags.data
       tags = tag_string.split(",")
       for tag in tags:
           post_tag = add_tags(tag)
           print post_tag
           post.tags.append(post_tag)
       db.session.add(post)
       db.session.commit()
       flash (u'New Post Created!', 'alert-info')
    return render_template('new_post.html',
                title='Admin-New Post',
                form=post_form)

def add_tags(tag):
    existing_tag = Tag.query.filter(Tag.name == tag.lower())
    """if it does return existing tag objec to list"""
    if existing_tag is not None:
        return existing_tag
    else:
       new_tag = Tag()
       new_tag.name = tag.lower()
       return new_tag

【问题讨论】:

【参考方案1】:

这个:

existing_tag = Tag.query.filter(Tag.name == tag.lower())
"""if it does return existing tag objec to list"""
if existing_tag is not None:
    return existing_tag

不返回Tag,而是返回Query。你想Tag.query.filter(...).one_or_none() 来获取标签本身。

【讨论】:

谢谢!明白了,回到文档我去弄清楚查询是如何工作的。

以上是关于Flask-SQLAlchemy 多对多插入的主要内容,如果未能解决你的问题,请参考以下文章

Flask sqlalchemy 多对多插入数据

使用flask-restplus在flask-SQLAlchemy中创建多对多关联表时出错

flask-sqlalchemy 一对一,一对多,多对多操作

sql 多对多关系中插入行时如何解决死锁问题?

通过链接到SQL Server数据库的MS Access以多对多关系插入数据(中间表)

Flask-SQLAlchemy数据库操作