在 Peewee 模型 Python 中创建 "query methods"

Create "query methods" in Peewee Models Python

我在 Flask 项目中使用 Peewee 进行 MySQL 连接。我想知道是否可以在模型的方法中进行查询。这将使路由代码更清晰,例如:

Person.py:

from peewee import *

db = SqliteDatabase('people.db')

class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = db # This model uses the "people.db" database.

    def getPersonByName(name):
        #logic to get persons by name
        #return result

Server.py:

 .
 .
 .
 @app.route('/<name>')
 def index(name):
     persons = Person.getPersonByName(name)
     return render_template('names.html', persons=persons)

可以将自定义方法添加到模型中以进行查询,从而使模型保持胖而视图保持苗条。

class Person(Model):
    ...

    @classmethod
    def get_person_by_name(cls, name):
        result = cls.select().where(cls.name == name)
        return result


 @app.route('/<name>')
 def index(name):
     persons = Person.get_person_by_name(name)
     return render_template('names.html', persons=persons)