Python’s SQLAlchemy vs Other ORMs[转发 4]peewee

peewee

peewee is a small, expressive ORM. Compared to other ORMs, peewee focuses on the principal of minimalism where the API is simple and the library is easy to use and understand.

 1 pip install peewee
 2 Downloading/unpacking peewee
 3 Downloading peewee-2.1.7.tar.gz (1.1MB): 1.1MB downloaded
 4 Running setup.py egg_info for package peewee
 5  
 6 Installing collected packages: peewee
 7 Running setup.py install for peewee
 8 changing mode of build/scripts-2.7/pwiz.py from 644 to 755
 9  
10 changing mode of /Users/xiaonuogantan/python2-workspace/bin/pwiz.py to 755
11 Successfully installed peewee
12 Cleaning up...

To create a database model mapping, we implement a Person class and an Address class that map to the corresponding database tables.

 1 >>> from peewee import SqliteDatabase, CharField, ForeignKeyField, Model
 2 >>>
 3 >>> db = SqliteDatabase(':memory:')
 4 >>>
 5 >>> class Person(Model):
 6 ...     name = CharField()
 7 ...     
 8 ...     class Meta:
 9 ...         database = db
10 ...
11 >>>
12 >>> class Address(Model):
13 ...     address = CharField()
14 ...     person = ForeignKeyField(Person)
15 ...
16 ...     class Meta:
17 ...         database = db
18 ...
19 >>> Person.create_table()
20 >>> Address.create_table()

To insert objects into the database, we instantiate the objects and call their save() methods. From object creation point of view, peewee is very similar to Django.

1 >>> p = Person(name='person')
2 >>> p.save()
3 >>> a = Address(address='address', person=p)
4 >>> a.save()

To get or retrieve the objects from the database, we select the objects from their respective classes.

 

1 >>> person = Person.select().where(Person.name == 'person').get()
2 >>> person
3 >>>
4 >>> print '%r, %r' % (person.id, person.name)
5 1, u'person'
6 >>> address = Address.select().where(Address.person == person).get()
7 >>> print '%r, %r' % (address.id, address.address)
8 1, u'address'

 

posted @ 2016-11-30 10:08  Brian Tan  阅读(628)  评论(0编辑  收藏  举报