如何在具有多对多关系的SQLAlchemy表中插入数据?

时间:2015-01-30 13:22:26

标签: python sqlalchemy many-to-many

我知道这个问题就在那里。但我请你帮我这个例子。 我有这个模型:

ItemTable = Table('ItemTable', Base.metadata,
    Column('post_id', Integer, ForeignKey('post.id')),
    Column('tags_id', Integer, ForeignKey('tag.id')))

class Post(Base):

    __tablename__ = 'post'
    id = Column(Integer, primary_key = True)
    title = Column(Text)
    body = Column(Text)
    timestamp = Column(DateTime, default=datetime.datetime.utcnow())
    user_id = Column(Integer, ForeignKey(User.id))
    tags = relationship('Tag', secondary=ItemTable, backref='post')

    def __init__(self,title=None,body=None):
        self.title = title
        self.body = body

    def __repr__(self):
        return '<Post %r>' % (self.title)

class Tag (Base):
    __tablename__ = 'tag'
    id = Column (Integer, primary_key = True)
    title = Column (Text)
    posts = relationship ('Post', secondary=ItemTable, backref='tag')

    def __init__(self,title=None):
        self.title = title

    def __repr__(self):
        return '<Tag %r>' % (self.title)

我尝试添加一个标签很少的帖子。我怎么能正确地做到这一点? 如果我这样做,我会收到错误:

  

AttributeError:'str'对象没有属性'_sa_instance_state'

class AddPost(BaseView):
def is_accessible(self):
    return g.user.is_authenticated()
@expose('/', methods=('GET', 'POST'))
def addpost_view(self):
    if not g.user.is_authenticated():
        return redirect(url_for('AdminView.login_view'))
    form = PostForm()
    if helpers.validate_form_on_submit(form):
        p=Post(title=form.title.data, body=form.text.data)
        for tag in form.tags.data.split(','):
            p.tags.append(tag)
        db_session.add(p)
        db_session.commit()
    self._template_args['form'] = form
    return self.render('admin/addpost.html')

1 个答案:

答案 0 :(得分:4)

您要将字符串附加到Post对象而不是Tag个对象。 问题出在这里:

for tag in form.tags.data.split(','):
    p.tags.append(tag)

它应该看起来像这样:

for t in form.tags.data.split(','):
    tag = Tag(....)
    p.tags.append(tag)