How to display the recipe with the highest like- Python Flask with Peewee

67 Views Asked by At

I am new to flask and I have created a flask api where user can upload recipe and also like recipes. To get the top recipe, I want sort recipe by the highest number of likes.

@app.route('/top_recipe', methods=['GET'])
def top_recipe():
    recipes = Recipe.select().join(Like).order_by(Like.recipe_id.desc())
    output = [recipe for recipe in recipes.dicts()]
    return jsonify({'Result':output})

I have used a foreign key in my model and below is the model. This gives me the recipe sorted by the id but not by the number of likes. I am using Peewee and Mysql for my db.

class Recipe(BaseModel):
    id = PrimaryKeyField(primary_key=True)
    name = CharField()
    description = CharField()
    ingredients = CharField()
    process = TextField()
    post_date = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
    poster_id = ForeignKeyField(Users, backref='recipe', lazy_load=False,             on_delete='CASCADE')
    image = CharField()
class Like(BaseModel):
    id = PrimaryKeyField(primary_key=True)
    recipe_id = ForeignKeyField(Recipe, backref='comment', lazy_load=False)
    post_date = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
    poster_id = ForeignKeyField(Users, backref='like', lazy_load=False)
class Users(BaseModel):
    id = PrimaryKeyField(primary_key=True)
    fullname = CharField()
    username = CharField()
    email = CharField()
    password_harsh = CharField()
    birthday = DateField()
    gender = CharField()
    profile = CharField()
1

There are 1 best solutions below

0
On

This is covered in the docs. Please read them! http://docs.peewee-orm.com/en/latest/peewee/querying.html#aggregating-records

query = (Recipe.select(Recipe, fn.COUNT(Like.id).alias('likes'))
         .join(Like, JOIN.LEFT_OUTER)
         .order_by(fn.COUNT(Like.id).desc()))