Created
February 19, 2021 01:23
-
-
Save MariaCarolinass/4c05a6aeb4a750918a23f5b7bc069f24 to your computer and use it in GitHub Desktop.
Ordernar os usuários pela quantidade de postagens que ele cadastrou
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User(db.Model, UserMixin): | |
id = db.Column(db.Integer, primary_key=True) | |
nickname = db.Column(db.String(200), unique=True) | |
posts = db.relationship('Post', backref='author', lazy='dynamic') | |
def __repr__(self): | |
return '{}'.format(self.nickname) | |
class Post(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
title = db.Column(db.String(200), index=True, unique=True) | |
user_id = db.Column(db.Integer, db.ForeignKey('user.id')) | |
def __repr__(self): | |
return '{}'.format(self.title) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import func | |
@bp.route('/user', methods=['GET', 'POST']) | |
def user(): | |
users = db.session.query(User, func.count(Post.user_id)).join(User.posts).limit(15).all() | |
return render_template('users.html', users=users, title=(_('Usuários Ordenados'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/370174/sqlalchemy-with-count-group-by-and-order-by-using-the-orm