创建“查询方法";在Peewee模型Python中 [英] Create "query methods" in Peewee Models Python
本文介绍了创建“查询方法";在Peewee模型Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Flask项目中将Peewee用于MySQL连接.我想知道是否可以在模型的方法中进行查询.这样可以使路由代码更整洁,例如:
i'm using Peewee for MySQL connection in a flask project. I would like to know if it's possible to make querys in Method of a model. That would make the route code cleaner, For Example:
Person.py:
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:
Server.py:
.
.
.
@app.route('/<name>')
def index(name):
persons = Person.getPersonByName(name)
return render_template('names.html', persons=persons)
推荐答案
可以将自定义方法添加到模型中以进行查询,以便使模型保持胖状态,保持视图简洁.
Custom methods can be added to a model to make queries so that models are kept fat and views kept slim.
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)
这篇关于创建“查询方法";在Peewee模型Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文