I am using flask to make a blog while learning flask. (An article can have multiple tags, and one tag can correspond to multiple articles, so I adopted the many to many relationship here according to the Internet), flask-sqlalchemy since The paginate method can only support flask_sqlalchemy.BaseQuery objects for pagination. However, I use tags in a multi-pair relationship to find all the article objects associated with the tag. The object is a list, so paging cannot be done. . . What should I do if I want to paginate now?
Should I write a paging myself now? I hope some kind-hearted experts can give me some advice on what the general idea is.
example:
#多对多关系中的两个表之间的一个关联表
tags = db.Table('post_tags',
db.Column('post_id',db.Integer,db.ForeignKey('posts.id')),
db.Column('tag_id',db.Integer,db.ForeignKey('tag.id'))
)
# 发表文章模型
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255))
body = db.Column(db.Text())
body_html = db.Column(db.Text())
created = db.Column(db.DateTime)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
comments = db.relationship('Comment', backref='post',lazy='dynamic') # 关联评论
tags = db.relationship('Tag',secondary=tags,backref=db.backref('posts',lazy='dynamic'))#多对多关联
def __repr__(self):
return "<post_id={0}>".format(self.id)
#标签
class Tag(db.Model):
__tablename__ = 'tag'
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(255))\
def __repr__(self):
return "{0}".format(self.title)
伊谢尔伦2017-06-12 09:24:47
I said pagination is stress-free. You can definitely use pagination
>>> r=Role.query.get(1)
>>> r
manager
>>> r.users
<sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x7f5ae257a510>
>>> r.users.paginate(1, 20, None)
<flask_sqlalchemy.Pagination object at 0x7f5ae1829150>
User and Role are many-to-many, and I didn’t find the problem mentioned by the original poster.