gino.crud module

class gino.crud.Alias(model, *args, **kwargs)

Bases: object

Experimental proxy for table alias on model.

load(*column_names, **relationships)
class gino.crud.CRUDModel(**values)

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.

classmethod alias(*args, **kwargs)

Experimental proxy for table alias on model.


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()

Deprecated since version 0.7.6: Use lookup() instead.

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()
  • 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.


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


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


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

  • 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.

classmethod distinct(*columns)

Experimental loader feature to yield only distinct instances by given columns.

async classmethod get(ident, bind=None, timeout=<object object>)

Get an instance of this model class by primary key.

For example:

user = await User.get(request.args.get('user_id'))
  • ident – Value of the primary key. For composite primary keys this should be a tuple of values for all keys in database order, or a dict of names (or position numbers in database order starting from zero) of all primary keys to their values.

  • 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.


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

classmethod in_query(query)

Convenient method to get a Model object when using subqueries.

Though with filters and aggregations, subqueries often return same columns as the original table, but SQLAlchemy could not recognize them as the columns are in subqueries, so technically they’re columns in the new “table”.

With this method, the columns are loaded into the original models when being used in subqueries. For example:

query = query.alias('users')
MyUser = User.in_query(query)

loader = MyUser.distinct(
users = await query.gino.load(loader).all()
classmethod load(*column_names, **relationships)

Populates a loader.Loader instance to be used by the loader execution option in order to customize the loading behavior to load specified fields into instances of this model.

The basic usage of this method is to provide the loader execution option (if you are looking for reloading the instance from database, check get() or query) for a given query.

This method takes both positional arguments and keyword arguments with very different meanings. The positional arguments should be column names as strings, specifying only these columns should be loaded into the model instance (other values are discarded even if they are retrieved from database). Meanwhile, the keyword arguments should be loaders for instance attributes. For example:

u = await User.query.gino.load(User.load('id', 'name')).first()


gino.load is a shortcut for setting the execution option loader.

This will populate a User instance with only id and name values, all the rest are simply None even if the query actually returned all the column values.

q = User.join(Team).select()
u = await q.gino.load(User.load(team=Team)).first()

This will load two instances of model User and Team, returning the User instance with set to the Team instance.

Both positional and keyword arguments can be used ath the same time. If they are both omitted, like Team.load(), it is equivalent to just Team as a loader.

Additionally, a loader.Loader instance can also be used to generate queries, as its structure is usually the same as the query:

u = await User.load(team=Team).query.gino.first()

This generates a query like this:

SELECT, ...,, ...
  FROM users LEFT JOIN teams
    ON ...

The Loader delegates attributes on the query, so .query can be omitted. The LEFT JOIN is built-in behavior, while the ON clause is generated based on foreign key. If there is no foreign key, or the condition should be customized, you can use this:

u = await User.load(
    team=Team.on(User.team_id ==

And you can use both load() and on() at the same time in a chain, in whatever order suits you.


Generate where-clause expression to locate this model instance.

By default this method uses current values of all primary keys, and you can override it to behave differently. Most instance-level CRUD operations depend on this method internally. Particularly while lookup() is called in update(), the where condition is used in UpdateRequest.apply(), so that queries like UPDATE ... SET id = NEW WHERE id = OLD could work correctly.


New in version 0.7.6.

classmethod none_as_none(enabled=True)
classmethod on(on_clause)

Customize the on-clause for the auto-generated outer join query.


This has no effect when provided as the loader execution option for a given query.

See also



Get a SQLAlchemy query clause of the table behind this model. This equals to[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.


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'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'age').gino.scalar()

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



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.QueryModel

Bases: type

Metaclass of Model classes used for subqueries.

class gino.crud.UpdateRequest(instance: gino.crud.CRUDModel)

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.

async apply(bind=None, timeout=<object object>)

Apply pending updates into database by executing an UPDATE SQL.

  • 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.


self for chaining calls.


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()


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.