model

class aiomyorm.model.Model(_new_created: bool = True, _pk_value=None, **kwargs)

The basic model class.

__table__

The table name of this model.If you do not set this attribute, class name will be used by default.

__auto__

If true, fields will automatically retrieved from the table, default False. Warnings: __auto__ dose not support sqlite.

the field you define

All the fields you define. In class it will be field while in instance it is the value of this field.

classmethod aggregate(*args, group_by: Union[str, aiomyorm.field.Field, None] = None, conn=None, **kwargs) → Union[List[Dict[KT, VT]], Dict[KT, VT], NoReturn]

Aggregate query.

Parameters:
  • args

    aggregate function, it’s alias will be taken as (function)__(field name), e.g. MAX__age. you can use the follow aggregate function:

    Max(), Min(), Count(), Avg(), Sum()
    
  • group_by (str) – Same as sql, and only allow one field.
  • kwargs – key is the alias of this aggregate field,and value is the aggregate function.
  • conn – custom connection (this parameter is optional)
Returns:

If the group_by parameter is not specified, will return a dict which key is it’s alias and value is it’s result. If the group_by parameter is specified, will return a dict which key is the result of the group_by field in each group, and value is a dict as same as the first situation.

Sample:

you can run this code:

from model import Max,Count,Min,Avg
async def run():
    rs = await Test.filter(grade=3).aggregate(Max('age'), minage=Min('age'), avgage=Avg('age'),
                                              groupnum=Count(), group_by='birth_place')
    import pprint
    pprint.pprint(rs)

asyncio.get_event_loop().run_until_complete(run())

you will get the result:

{'someplace': {'MAX__age': 20, 'avgage': 20.0, 'groupnum': 1, 'minage': 20},
 'someplace1': {'MAX__age': 23, 'avgage': 20.5, 'groupnum': 2, 'minage': 18},
 'someplace3': {'MAX__age': 17, 'avgage': 17.0, 'groupnum': 1, 'minage': 17}}
classmethod change_db(db: str)

Change the database this model belongs to.

Warnings: not support sqlite

classmethod change_db_one_time(db: str)

Change the database one time.

You can use this method temporarily change the database this model belongs in the next query or modification.

e.g.:

r = await Model.change_db_one_time(newdb).find()

This query will be performed in newdb.

Warnings: not support sqlite

classmethod create_table()

Create this table in current database.

classmethod delete(conn=None) → int

Delete objects from database.

You can use filter() and other method to filter the objects that want to delete, just as you did in find().

Parameters:conn – custom connection (this parameter is optional)
Returns:(int) Total number of objects deleted.
classmethod distinct()

Add DISTINCT condition for your query.

classmethod exclude(**kwargs) → None

Exclude filter your query.

Parameters:kwargs – the field you wang to exclude and it’s value.
Raises:ValueError – An error occurred when argument is not a Field.
classmethod execute(sql: str, args: Union[list, tuple, None] = (), conn=None) → int

Execute a insert,update or delete query, and return the number of affected rows.You can use this method when you encounter a query that ORM cannot complete.

Parameters:
  • sql (str) – a sql statement, use ? as placeholder.
  • args (list or tuple) – argument in placeholder.
  • conn – use this parameter to specify a custom connection.
Returns:

(int) affected rows.

classmethod filter(**kwargs) → None

Filter your query,correspond to where key=value in sql.

Parameters:Kwargs – The field you wang to filter and it’s value.
Raises:ValueError – An error occurred when argument is not a Field.
classmethod find(conn=None)

Do select.This method will return a list of YourModel objects.

Parameters:conn – custom connection (this parameter is optional)
Returns:(list) A list of YourModel objects.If no record can be found, will return an empty list.
classmethod find_first(conn=None)

Do select.This method will directly return one YourModel object instead of a list.

Parameters:conn – custom connection (this parameter is optional)
Returns:(Model) One YourModel object.If no record can be found, will return None.
classmethod flex_exclude(*conditions)

Exclude your query flexibly, such as ‘>’ ‘<’ and so on.

Parameters:field you wang to exclude and it's value. (The) –
You can use the following methods:
same as flex_filtter()
Raises:ValueError – An error occurred when you use it in the wrong way.
classmethod flex_filter(*conditions)

Filter your query flexibly, such as ‘>’ ‘<’ and so on.

Parameters:conditions – The field you wang to filter and it’s value.

You can use the following methods:

flex_filter(Table.Field>100)               --in sql-->  where Table.Field>100
flex_filter(Table.Field>=100)              --in sql-->  where Table.Field>=100
flex_filter(Table.Field==100)              --in sql-->  where Table.Field=100
flex_filter(Table.Field<=100)              --in sql-->  where Table.Field<=100
flex_filter(Table.Field<100)               --in sql-->  where Table.Field<100
flex_filter(Table.Field.like('%abc%'))     --in sql-->  where Table.Field LIKE '%abc%'
flex_filter(Table.Field.start_with(abc))   --in sql-->  where Table.Field LIKE 'abc%'
flex_filter(Table.Field.end_with(abc))     --in sql-->  where Table.Field LIKE '%abc'
flex_filter(Table.Field.has('abc'))        --in sql-->  where Table.Field LIKE '%abc%'
Raises:ValueError – An error occurred when you use it in the wrong way.
classmethod get_db()

Get the database this model belongs to.

classmethod get_fields()

Get the names of all fields

classmethod get_mapping()

Get the fields mapping.

classmethod get_primary_key()

Get the name of the primary key

classmethod insert(*insert_objects, conn=None) → int

Insert objects to database.

This method can insert multiple objects and access the database only once.

Parameters:
  • insert_objects (Model) – One or more object of this Model.They must have the same format.
  • conn – custom connection (this parameter is optional)
Raise:
ValueError: An error occurred when argument is not the object of this model. RuntimeError: An error occurred when arguments do not have the same format.
Returns:(int) Affected rows.
classmethod or_connect()

Connect your filter br ‘OR’ rather than ‘AND’.

classmethod order_by(*args)

Sort query results.

By default, it will be sorted from small to large. You can sort it from large to small by adding ‘-‘.

Parameters:args – (str) The sorting basis you specified.

Example:

User.query('id').order_by('id').find()
# will sort by id from small to large
User.query('id').order_by('-id').find()
# will sort by id from large to small
classmethod pk_find(pk_value, conn=None)

Get one object by primary key.

You should specify the primary key in this method. All the restrictions you have made before, except “query()”, will not take effect. This method will directly return one YourModel object.

Parameters:
  • pk_value – value of primary key.
  • conn – custom connection (this parameter is optional)
Returns:

(Model) One YourModel object.If no record can be found, will return None.

classmethod query(*args) → None

Choice the field you want to query.

All the query method such as find() will query all the fields by default, so if you want to query all fields, just do not use this method.

Parameters:args – The field you wang to query.You can use Model.Field or the name of field.

e.g.:

r = await User.query(User.id).find()
r = await User.query('id').find()
Raises:ValueError – An error occurred when argument is not a Field.
remove(conn=None) → NoReturn

Remove this object from database.

Parameters:conn – custom connection (this parameter is optional)
Raise:
RuntimeError: An error occurred when can not find a primary key of this object. since every object queried from the database will query primary key explicitly or implicitly, this error will only appear when the newly created object calls the remove() method, which itself is the wrong use. To delete an object without querying in advance, use delete() method.
Returns:None
save(conn=None) → NoReturn

Save this object to database.

Parameters:conn – custom connection (this parameter is optional)
Raise:
RuntimeError: An error occurred when failed to save this object. AttributeError: An error occurred when primary key has been changed, which is not allowed in this method, use update().
Returns:None
classmethod select(sql: str, args: Union[list, tuple, None] = (), conn=None) → list

Execute a select query, and turn the result into a model object. You can use this method when you encounter a query that ORM cannot complete

Parameters:
  • sql (str) – a sql statement, use ? as placeholder.
  • args (list or tuple) – argument in placeholder.
  • conn – use this parameter to specify a custom connection.
Returns:

(list) a list of model objects.

classmethod update(conn=None, **kwargs) → int

Update objects to database.

You can use filter() and other method to filter the objects that want to update, just as you did in find().

Parameters:conn – custom connection (this parameter is optional)
Returns:(int) Total number of objects updated.
classmethod use(conn=None)

Specify a connection.