当前位置: 首页 > 工具软件 > Pony ORM > 使用案例 >

Python’s SQLAlchemy vs Other ORMs[转发 5] PonyORM

景书
2023-12-01

PonyORM

PonyORM allows you to query the database using Python generators. These generators are translated into SQL and the results are automatically mapped into Python objects. Writing queries as Python generators makes it easy for programmers to quickly construct certain queries.

For example, let's use PonyORM to query the previous Person and Address models in a SQLite database.

 1 >>> from pony.orm import Database, Required, Set
 2 >>>
 3 >>> db = Database('sqlite', ':memory:')
 4 >>>
 5 >>>
 6 >>> class Person(db.Entity):
 7 ...     name = Required(unicode)
 8 ...     addresses = Set("Address")
 9 ...
10 >>>
11 >>> class Address(db.Entity):
12 ...     address = Required(unicode)
13 ...     person = Required(Person)
14 ...
15 >>> db.generate_mapping(create_tables=True)

 

Now we have a SQLite database in memory and two tables mapped to the db object, we can insert two objects into the database.

1 >>> p = Person(name="person")
2 >>> a = Address(address="address", person=p)
3 >>> db.commit()

The call db.commit() actually commits the new objects p and a into the database. Now we can query the database using the generator syntax.

1 >>> from pony.orm import select
2 >>> select(p for p in Person if p.name == "person")[:]
3 [Person[1]]
4 >>> select(p for p in Person if p.name == "person")[:][0].name
5 u'person'
6 >>> select(a for a in Address if a.person == p)[:]
7 [Address[1]]
8 >>> select(a for a in Address if a.person == p)[:][0].address
9 u'address'

 

转载于:https://www.cnblogs.com/tanxstar/p/6116450.html

 类似资料: