Entity methods
class Entity
classmethod __getitem__()
Return an entity instance selected by its primary key. Raises the
ObjectNotFound
exception if there is no such object. Example:p = Product[123]
For entities with a composite primary key, use a comma between the primary key values:
item = OrderItem[123, 456]
If object with the specified primary key was already loaded into the
db_session()
cache, Pony returns the object from the cache without sending a query to the database.delete()
Delete the entity instance. The instance will be marked as deleted and then will be deleted from the database during the
flush()
function, which is issued automatically on committing the current transaction when exiting from the most outerdb_session()
or before sending the next query to the database.Order[123].delete()
classmethod describe()
Return a string with the entity declaration.
>>> print(OrderItem.describe())
class OrderItem(Entity):
quantity = Required(int)
price = Required(Decimal)
order = Required(Order)
product = Required(Product)
PrimaryKey(order, product)
classmethod drop_table(with_all_data=False)
Drops the table which is associated with the entity in the database. If the table is not empty and
with_all_data=False
, the method raises theTableIsNotEmpty
exception and doesn’t delete anything. Setting thewith_all_data=True
allows you to delete the table even if it is not empty.If you need to delete an intermediate table created for many-to-many relationship, you have to call the method
select()
of the relationship attribute.classmethod exists(\args, **kwargs*)
Returns
True
if an instance with the specified condition or attribute values exists andFalse
otherwise.Product.exists(price=1000)
Product.exists(lambda p: p.price > 1000)
flush()
Save the changes made to this object to the database. Usually Pony saves changes automatically and you don’t need to call this method yourself. One of the use cases when it might be needed is when you want to get the primary key value of a newly created object which has autoincremented primary key before commit.
classmethod get(\args, **kwargs*)
Extract one entity instance from the database.
If the object with the specified parameters exists, then returns the object. Returns
None
if there is no such object. If there are more than one objects with the specified parameters, raises theMultipleObjectsFoundError: Multiple objects were found. Use select(...) to retrieve them
exception. Examples:Product.get(price=1000)
Product.get(lambda p: p.name.startswith('A'))
classmethod get_by_sql(sql, globals=None, locals=None)
Select entity instance by raw SQL.
If you find that you cannot express a query using the standard Pony queries, you always can write your own SQL query and Pony will build an entity instance(s) based on the query results. When Pony gets the result of the SQL query, it analyzes the column names which it receives from the database cursor. If your query uses
SELECT * ...
from the entity table, that would be enough for getting the necessary attribute values for constructing entity instances. You can pass parameters into the query, see Using the select_by_sql() and get_by_sql() methods for more information.classmethod get_for_update(\args, **kwargs, nowait=False, skip_locked=False*)
Note
nowait and skip_locked parameters are mutually exclusive.
Parameters
nowait (bool) – prevent the operation from waiting for other transactions to commit. If a selected row(s) cannot be locked immediately, the operation reports an error, rather than waiting.
skip_locked (bool) – add SKIP LOCKED option to FOR UPDATE clause
Locks the row in the database using the
SELECT ... FOR UPDATE
SQL query. Ifnowait=True
, then the method will throw an exception if this row is already blocked. Ifnowait=False
, then it will wait if the row is already blocked.If you need to use
SELECT ... FOR UPDATE
for multiple rows then you should use thefor_update()
method.get_pk()
Get the value of the primary key of the object.
>>> c = Customer[1]
>>> c.get_pk()
1
If the primary key is composite, then this method returns a tuple consisting of primary key column values.
>>> oi = OrderItem[1,4]
>>> oi.get_pk()
(1, 4)
load(\args*)
Load all lazy and non-lazy attributes, but not collection attributes, which were not retrieved from the database yet. If an attribute was already loaded, it won’t be loaded again. You can specify the list of the attributes which need to be loaded, or it’s names. In this case Pony will load only them:
obj.load(Person.biography, Person.some_other_field)
obj.load('biography', 'some_other_field')
classmethod select(lambda=None, \*kwargs*)
Select objects from the database in accordance with the condition specified in lambda or keyword arguments, or all objects if lambda function is not specified.
The
select()
method returns an instance of theQuery
class. Entity instances will be retrieved from the database once you start iterating over theQuery
object.This query example returns all products with the price greater than 100 and which were ordered more than once:
Product.select(lambda p: p.price > 100 and count(p.order_items) > 1)
Product.select(item_type='TV')
Note
Since version 0.7.7 select can also be used with keyword arguments
classmethod select_by_sql(sql, globals=None, locals=None)
Select entity instances by raw SQL. See Using the select_by_sql() and get_by_sql() methods for more information.
classmethod select_random(limit)
Select
limit
random objects. This method uses the algorithm that can be much more effective than usingORDER BY RANDOM()
SQL construct. The method uses the following algorithm:Determine max id from the table.
Generate random ids in the range (0, max_id]
Retrieve objects by those random ids. If an object with generated id does not exist (e.g. it was deleted), then select another random id and retry.
Repeat the steps 2-3 as many times as necessary to retrieve the specified amount of objects.
This algorithm doesn’t affect performance even when working with a large number of table rows. However this method also has some limitations:
The primary key must be a sequential id of an integer type.
The number of “gaps” between existing ids (the count of deleted objects) should be relatively small.
The
select_random()
method can be used if your query does not have any criteria to select specific objects. If such criteria is necessary, then you can use theQuery.random()
method.set(\*kwargs*)
Assign new values to several object attributes at once:
Customer[123].set(email='new@example.com', address='New address')
This method also can be convenient when you want to assign new values from a dictionary:
d = {'email': 'new@example.com', 'address': 'New address'}
Customer[123].set(**d)
to_dict(only=None, exclude=None, with_collections=False, with_lazy=False, related_objects=False)
Return a dictionary with attribute names and its values. This method can be used when you need to serialize an object to JSON or other format.
By default this method doesn’t include collections (to-many relationships) and lazy attributes. If an attribute’s values is an entity instance then only the primary key of this object will be added to the dictionary.
Parameters
only (list|str) – use this parameter if you want to get only the specified attributes. This argument can be used as a first positional argument. You can specify a list of attribute names
obj.to_dict(['id', 'name'])
, a string separated by spaces:obj.to_dict('id name')
, or a string separated by spaces with commas:obj.to_dict('id, name')
.exclude (list|str) – this parameter allows you to exclude specified attributes. Attribute names can be specified the same way as for the
only
parameter.related_objects (bool) – by default, all related objects represented as a primary key. If
related_objects=True
, then objects which have relationships with the current object will be added to the resulting dict as objects, not their primary keys. It can be useful if you want to walk the related objects and call theto_dict()
method recursively.with_collections (bool) – by default, the resulting dictionary will not contain collections (to-many relationships). If you set this parameter to
True
, then the relationships to-many will be represented as lists. Ifrelated_objects=False
(which is by default), then those lists will consist of primary keys of related instances. Ifrelated_objects=True
then to-many collections will be represented as lists of objects.with_lazy (bool) – if
True
, then lazy attributes (such as BLOBs or attributes which are declared withlazy=True
) will be included to the resulting dict.related_objects – By default all related objects are represented as a list with their primary keys only. If you want to see the related objects instances, you can specify
related_objects=True
.
For illustrating the usage of this method we will use the eStore example which comes with Pony distribution. Let’s get a customer object with the id=1 and convert it to a dictionary:
>>> from pony.orm.examples.estore import *
>>> c1 = Customer[1]
>>> c1.to_dict()
{'address': u'address 1',
'country': u'US',
'email': u'john@example.com',
'id': 1,
'name': u'John Smith',
'password': u'***'}
If we don’t want to serialize the password attribute, we can exclude it this way:
>>> c1.to_dict(exclude='password')
{'address': u'address 1',
'country': u'US',
'email': u'john@example.com',
'id': 1,
'name': u'John Smith'}
If you want to exclude more than one attribute, you can specify them as a list:
exclude=['id', 'password']
or as a string:exclude='id, password'
which is the same asexclude='id password'
.Also you can specify only the attributes, which you want to serialize using the parameter
only
:>>> c1.to_dict(only=['id', 'name'])
{'id': 1, 'name': u'John Smith'}
>>> c1.to_dict('name email') # 'only' parameter as a positional argument
{'email': u'john@example.com', 'name': u'John Smith'}
By default the collections are not included to the resulting dict. If you want to include them, you can specify
with_collections=True
. Also you can specify the collection attribute in theonly
parameter:>>> c1.to_dict(with_collections=True)
{'address': u'address 1',
'cart_items': [1, 2],
'country': u'USA',
'email': u'john@example.com',
'id': 1,
'name': u'John Smith',
'orders': [1, 2],
'password': u'***'}
By default all related objects (cart_items, orders) are represented as a list with their primary keys. If you want to see the related objects instances, you can specify
related_objects=True
:>>> c1.to_dict(with_collections=True, related_objects=True)
{'address': u'address 1',
'cart_items': [CartItem[1], CartItem[2]],
'country': u'USA',
'email': u'john@example.com',
'id': 1,
'name': u'John Smith',
'orders': [Order[1], Order[2]],
'password': u'***'}