【问题标题】:Create "query methods" in Peewee Models Python在 Peewee Models Python 中创建“查询方法”
【发布时间】:2020-01-31 03:02:49
【问题描述】:

我在烧瓶项目中使用 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

服务器.py:

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

【问题讨论】:

    标签: python flask peewee


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 2021-12-25
      • 2018-04-25
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多