R
R
RedStone2017-03-25 17:59:12
Flask
RedStone, 2017-03-25 17:59:12

How to update many to many tables in SQLAlchemy?

I’m making a flask blog for myself, I’ve added posts, I can’t figure out how to update the post tags now. The post and tags are connected via a many to many link.

models

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

class Post(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  title = db.Column(db.String(150), index = True)
  post_preview = db.Column(db.String(500), index = True, unique = True)
  post_body = db.Column(db.Text(), index = True, unique = True)
  date = db.Column(db.DateTime(), index = True)
  tags = db.relationship('Tag', secondary=tags,
      backref=db.backref('posts', lazy='dynamic'))

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


class Tag(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  text = db.Column(db.String(50), index = True)

  def __repr__(self):
    return self.text

  def __init__(self, txt):
    self.text = txt


How do I update a post?
Post.query.filter_by(id = post_id).update({"title":form.title.data, "post_preview":form.post_preview.data, "post_body":form.post_body.data})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
User2017, 2017-03-25
@User2017

maybe this will help you https://techarena51.com/index.php/many-to-many-rel...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question