Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
wiki2:python:flask:mongoalchemy [2015/08/08 13:47] alfred [Queries] |
wiki2:python:flask:mongoalchemy [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 6: | Línea 6: | ||
| ===== Use ===== | ===== Use ===== | ||
| + | ==== Initialization ==== | ||
| + | |||
| <code python> | <code python> | ||
| from flask import Flask | from flask import Flask | ||
| Línea 22: | Línea 24: | ||
| </code> | </code> | ||
| + | There are other ways to initialize it: | ||
| + | <code python> | ||
| + | app = Flask(__name__) | ||
| + | db = MongoAlchemy(app) | ||
| + | </code> | ||
| + | <code python> | ||
| + | db = MongoAlchemy() | ||
| + | def init_app(): | ||
| + | app = Flask(__name__) | ||
| + | db.init_app(app) | ||
| + | return app | ||
| + | </code> | ||
| ==== Create, update, delete ==== | ==== Create, update, delete ==== | ||
| Now you can create authors and books: | Now you can create authors and books: | ||
| Línea 56: | Línea 70: | ||
| </code> | </code> | ||
| + | === Advanced === | ||
| + | You can create your own queries: | ||
| + | <code python> | ||
| + | from flask.ext.mongoalchemy import BaseQuery | ||
| + | from application import db | ||
| + | |||
| + | class MyCustomizedQuery(BaseQuery): | ||
| + | |||
| + | def get_johns(self): | ||
| + | return self.filter(self.type.first_name == 'John') | ||
| + | |||
| + | class Person(db.Document): | ||
| + | query_class = MyCustomizedQuery | ||
| + | name = db.StringField() | ||
| + | </code> | ||
| + | |||
| + | There are other functions: | ||
| + | * first_or_404() | ||
| + | * get(mongo_id) | ||
| + | * get_or_404(mongo_id) | ||
| + | |||
| + | === Pagination === | ||
| + | You can call a method for a query: ''paginate(page, per_page=20, error_out=True)''. This method returns a ''Pagination'' object in which you can call... | ||
| + | * has_next() | ||
| + | * has_prev() | ||
| + | * items = None | ||
| + | * next(error_out=False) | ||
| + | * next_num | ||
| + | * page = None | ||
| + | * pages | ||
| + | * per_page = None | ||
| + | * prev(error_out=False) | ||
| + | * prev_num | ||
| + | * query = None | ||
| + | * total = None | ||
| + | |||
| + | [[https://pythonhosted.org/Flask-MongoAlchemy/index.html#flask.ext.mongoalchemy.Pagination.has_next|Documentation for these methods]] | ||
| ===== Configuration ===== | ===== Configuration ===== | ||
| <code python> | <code python> | ||