python flask many to many table query capability

  • 2020-06-07 04:45:00
  • OfStack

In the study of flask, we will inevitably encounter many-to-table queries, and Today I also encountered this problem. So I thought about it for a long time. Also didn't think of a solution, tried a few kinds of methods, may be the limitation of thinking I give up, later, I was in baidu online, but found that baidu results and they want one set of gap, then I according to the baidu of train of thought, then I also explores the data structure to me, take a look at me how to query, first of all, for everyone to see the database code fragments, I wrote this, deepen the understanding.


post_class=db.Table('post_class',
  db.Column('post_id',db.Integer(),db.ForeignKey('posts.id')),
  db.Column('classifa_id',db.Integer(),db.ForeignKey('fenlei.id')))
class Post(db.Model):# The article table 
  __tablename__='posts'
  id=db.Column(db.Integer,primary_key=True,autoincrement=True)
  title=db.Column(db.String(255),unique=True)
  text=db.Column(db.Text())
  publish_date=db.Column(db.DateTime,default=datetime.datetime.now())
  user_id=db.Column(db.Integer,db.ForeignKey('users.id'))
  is_recomment=db.Column(db.Boolean,default=False)
  comments = db.relationship(
    'Comment',
    backref='posts',
    lazy='dynamic')
  tag = db.relationship(
    'Tag',
    secondary=posts_tags,
    backref=db.backref('posts', lazy='dynamic')
  )
  classname=db.relationship('Classifa',
    secondary=post_class,
    backref=db.backref('posts'))
  def __repr__(self):
    return "<Model Post `{}`>".format(self.title)
class Classifa(db.Model):# classification 
  __tablename__='fenlei'
  id=db.Column(db.Integer(),primary_key=True)
  name=db.Column(db.String(64))
  def __repr__(self):
    return self.name

There are 3 tables, one is a list of articles, the other one, is a classification table, let us think, 1 article may belong to multiple categories at the same time, so a classification may belong to multiple articles, so we all must understand this logic, then, my third table to display the many-to-many relationship, so we how to query, then in fact, I need now is I'm looking for a 1 to classification of all the articles below,

Let's take a look at my code


data=Classifa.query.filter_by(name=' The database ').first()
 data_post=data.posts

Here, I directly found this classification from the classification, and then through the third table to query the article belonging to this classification. In fact, here is very simple, may be my own brain short circuit at that time, do not know how to think is right, now it is actually so simple, but I ignored what. Come on, learn the way forward.


Related articles: