gino.crud module

class gino.crud.CRUDModel(**values)[source]

Bases: gino.declarative.Model

The base class for models with CRUD support.

Don’t inherit from this class directly, because it has no metadata. Use db.Model instead.

append_where_primary_key(q)[source]

Append where clause to locate this model instance by primary on the given query, and return the new query.

This is mostly used internally in GINO, but also available for such usage:

await user.append_where_primary_key(User.query).gino.first()

which is identical to:

await user.query.gino.first()
coroutine create(bind=None, timeout=<object object>, **values)

This create behaves a bit different on model classes compared to model instances.

On model classes, create will create a new model instance and insert it into database. On model instances, create will just insert the instance into the database.

Under the hood create() uses INSERT ... RETURNING ... to create the new model instance and load it with database default data if not specified.

Some examples:

user1 = await User.create(name='fantix', age=32)
user2 = User(name='gino', age=42)
await user2.create()
Parameters:
  • bind – A GinoEngine to execute the INSERT statement with, or None (default) to use the bound engine on the metadata (Gino).
  • timeout – Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
  • values – Keyword arguments are pairs of attribute names and their initial values. Only available when called on a model class.
Returns:

The instance of this model class (newly created or existing).

delete

Similar to update(), this delete is also different on model classes than on model instances.

On model classes delete is an attribute of type Delete for massive deletes, for example:

await User.delete.where(User.enabled.is_(False)).gino.status()

Similarly you can add a returning() clause to the query and it shall return the deleted rows as model objects.

And on model instances, delete() is a method to remove the corresponding row in the database of this model instance. and returns the status returned from the database:

print(await user.delete())  # e.g. prints DELETE 1

Note

delete() only removes the row from database, it does not affect the current model instance.

Parameters:
  • bind – An optional GinoEngine if current metadata (Gino) has no bound engine, or specifying a different GinoEngine to execute the DELETE.
  • timeout – Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
coroutine get(ident, bind=None, timeout=<object object>)[source]

Get an instance of this model class by primary key.

For example:

user = await User.get(request.args.get('user_id'))
Parameters:
  • ident – Value of the primary key. For composite primary keys this should be a tuple of values for all keys in database order.
  • bind – A GinoEngine to execute the INSERT statement with, or None (default) to use the bound engine on the metadata (Gino).
  • timeout – Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
Returns:

An instance of this model class, or None if no such row.

query = <sqlalchemy.sql.selectable.Select at 0x7fdc54ce4b70; Select object>

Get a SQLAlchemy query clause of the table behind this model. This equals to sqlalchemy.select([self.__table__]). If this attribute is retrieved on a model instance, then a where clause to locate this instance by its primary key is appended to the returning query clause. This model type is set as the execution option model in the returning clause, so by default the query yields instances of this model instead of database rows.

select()

Build a query to retrieve only specified columns from this table.

This method accepts positional string arguments as names of attributes to retrieve, and returns a Select for query. The returning query object is always set with two execution options:

  1. model is set to this model type
  2. return_model is set to False

So that by default it always return rows instead of model instances, while column types can be inferred correctly by the model option.

For example:

async for row in User.select('id', 'name').gino.iterate():
    print(row['id'], row['name'])

If select() is invoked on a model instance, then a WHERE clause to locate this instance by its primary key is appended to the returning query clause. This is useful when you want to retrieve a latest value of a field on current model instance from database:

db_age = await user.select('age').gino.scalar()
to_dict()[source]

Convenient method to generate a dict from this model instance.

Keys will be attribute names, while values are loaded from memory (not from database). If there are JSONProperty attributes in this model, their source JSON field will not be included in the returning dict - instead the JSON attributes will be.

See also

json_support

update

This update behaves quite different on model classes rather than model instances.

On model classes, update is an attribute of type Update for massive updates, for example:

await User.update.values(enabled=True).where(...).gino.status()

Like query, the update query also has the model execution option of this model, so if you use the returning() clause, the query shall return model objects.

However on model instances, update() is a method which accepts keyword arguments only and returns an UpdateRequest to update this single model instance. The keyword arguments are pairs of attribute names and new values. This is the same as UpdateRequest.update(), feel free to read more about it. A normal usage example would be like this:

await user.update(name='new name', age=32).apply()

Here, the await ... apply() executes the actual UPDATE SQL in the database, while user.update() only makes changes in the memory, and collect all changes into an UpdateRequest instance.

class gino.crud.UpdateRequest(instance)[source]

Bases: object

A collection of attributes and their new values to update on one model instance.

UpdateRequest instances are created by CRUDModel.update, don’t instantiate manually unless required. Every UpdateRequest instance is bound to one model instance, all updates are for that one specific model instance and its database row.

coroutine apply(bind=None, timeout=<object object>)[source]

Apply pending updates into database by executing an UPDATE SQL.

Parameters:
  • bind – A GinoEngine to execute the SQL, or None (default) to use the bound engine in the metadata.
  • timeout – Seconds to wait for the database to finish executing, None for wait forever. By default it will use the timeout execution option value if unspecified.
Returns:

self for chaining calls.

update(**values)[source]

Set given attributes on the bound model instance, and add them into the update collections for apply().

Given keyword-only arguments are pairs of attribute names and values to update. This is not a coroutine, calling update() will have instant effect on the bound model instance - its in-memory values will be updated immediately. Therefore this can be used individually as a shortcut to update several attributes in a batch:

user.update(age=32, disabled=True)

update() returns self for chaining calls to either apply() or another update(). If one attribute is updated several times by the same UpdateRequest, then only the last value is remembered for apply().

Updated values can be SQLAlchemy expressions, for example an atomic increment for user balance looks like this:

await user.update(balance=User.balance + 100).apply()

Note

Expression values will not affect the in-memory attribute value on update() before apply(), because it has no knowledge of the latest value in the database. After apply() the new value will be automatically reloaded from database with RETURNING clause.