Reputation: 275
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:
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)
Upvotes: 1
Views: 1204
Reputation: 38952
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)
Upvotes: 6