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:

    1. p = Product[123]

    For entities with a composite primary key, use a comma between the primary key values:

    1. 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 outer db_session() or before sending the next query to the database.

    1. Order[123].delete()
  • classmethod describe()

    Return a string with the entity declaration.

    1. >>> print(OrderItem.describe())
    2. class OrderItem(Entity):
    3. quantity = Required(int)
    4. price = Required(Decimal)
    5. order = Required(Order)
    6. product = Required(Product)
    7. 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 the TableIsNotEmpty exception and doesn’t delete anything. Setting the with_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 and False otherwise.

    1. Product.exists(price=1000)
    2. 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 the MultipleObjectsFoundError: Multiple objects were found. Use select(...) to retrieve them exception. Examples:

    1. Product.get(price=1000)
    2. 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. If nowait=True, then the method will throw an exception if this row is already blocked. If nowait=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 the for_update() method.

  • get_pk()

    Get the value of the primary key of the object.

    1. >>> c = Customer[1]
    2. >>> c.get_pk()
    3. 1

    If the primary key is composite, then this method returns a tuple consisting of primary key column values.

    1. >>> oi = OrderItem[1,4]
    2. >>> oi.get_pk()
    3. (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:

    1. obj.load(Person.biography, Person.some_other_field)
    2. 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 the Query class. Entity instances will be retrieved from the database once you start iterating over the Query object.

    This query example returns all products with the price greater than 100 and which were ordered more than once:

    1. Product.select(lambda p: p.price > 100 and count(p.order_items) > 1)
    2. 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 using ORDER BY RANDOM() SQL construct. The method uses the following algorithm:

    1. Determine max id from the table.

    2. Generate random ids in the range (0, max_id]

    3. 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 the Query.random() method.

  • set(\*kwargs*)

    Assign new values to several object attributes at once:

    1. 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:

    1. d = {'email': 'new@example.com', 'address': 'New address'}
    2. 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 the to_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. If related_objects=False (which is by default), then those lists will consist of primary keys of related instances. If related_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 with lazy=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:

    1. >>> from pony.orm.examples.estore import *
    2. >>> c1 = Customer[1]
    3. >>> c1.to_dict()
    4. {'address': u'address 1',
    5. 'country': u'US',
    6. 'email': u'john@example.com',
    7. 'id': 1,
    8. 'name': u'John Smith',
    9. 'password': u'***'}

    If we don’t want to serialize the password attribute, we can exclude it this way:

    1. >>> c1.to_dict(exclude='password')
    2. {'address': u'address 1',
    3. 'country': u'US',
    4. 'email': u'john@example.com',
    5. 'id': 1,
    6. '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 as exclude='id password'.

    Also you can specify only the attributes, which you want to serialize using the parameter only:

    1. >>> c1.to_dict(only=['id', 'name'])
    2. {'id': 1, 'name': u'John Smith'}
    3. >>> c1.to_dict('name email') # 'only' parameter as a positional argument
    4. {'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 the only parameter:

    1. >>> c1.to_dict(with_collections=True)
    2. {'address': u'address 1',
    3. 'cart_items': [1, 2],
    4. 'country': u'USA',
    5. 'email': u'john@example.com',
    6. 'id': 1,
    7. 'name': u'John Smith',
    8. 'orders': [1, 2],
    9. '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:

    1. >>> c1.to_dict(with_collections=True, related_objects=True)
    2. {'address': u'address 1',
    3. 'cart_items': [CartItem[1], CartItem[2]],
    4. 'country': u'USA',
    5. 'email': u'john@example.com',
    6. 'id': 1,
    7. 'name': u'John Smith',
    8. 'orders': [Order[1], Order[2]],
    9. 'password': u'***'}