Answer the question
In order to leave comments, you need to log in
How to correctly add data to a table via SQLALCHEMY many-to-many?
Good afternoon.
There is such a trivial model:
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)
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(form.title.data, form.text.data)
p.tags.append(form.tags.data.split(','))
db_session.add(p)
db_session.commit()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question