1
votes

Flask sqlalchemy many-to-many insert data

I've tried the above advice but continue to recieve the following error on the append of a many to many attribute when inserting a new post with tags.

Any direction would be most appreciated!

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

11:06:22 PM web.1 | File "/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/collections.py", line 1072, in append

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

11:06:22 PM web.1 | File "/home/trevor/Projects/trevorblog/venv/local /lib/python2.7/site-packages/sqlalchemy/orm/collections.py", line 1044, in __set

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

11:06:22 PM web.1 | File "/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/collections.py", line 716, in fire_append_event

11:06:22 PM web.1 | item, initiator)

11:06:22 PM web.1 | File "/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 936, in fire_append_event

11:06:22 PM web.1 | initiator or self._append_token or self._init_append_token())

11:06:22 PM web.1 | File "/home/trevor/Projects/trevorblog/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 1171, in 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' object has no attribute '_sa_instance_state'

Model.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

1 Answers

2
votes

This:

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

does not return a Tag, but a Query. You want to Tag.query.filter(...).one_or_none() to get the tag itself.