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'

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值