Python中peewee模块(一)

来源:互联网 发布:重复文件清理软件 编辑:程序博客网 时间:2024/05/01 07:48

前言

关于ORM框架:

简介:

对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。

对象关系映射(Object-Relational Mapping)提供了概念性的、易于理解的模型化数据的方法。ORM方法论基于三个核心原则: 简单:以最基本的形式建模数据。 传达性:数据库结构被任何人都能理解的语言文档化。 精确性:基于数据模型创建正确标准化了的结构。 典型地,建模者通过收集来自那些熟悉应用程序但不熟练的数据建模者的人的信息开发信息模型。建模者必须能够用非技术企业专家可以理解的术语在概念层次上与数据结构进行通讯。建模者也必须能以简单的单元分析信息,对样本数据进行处理。ORM专门被设计为改进这种联系。

ORM优势:

1.隐藏了数据访问细节,“封闭”的通用数据库交互,ORM的核心。他使得我们的通用数据库交互变得简单易行,并且完全不用考虑该死的SQL语句。快速开发,由此而来。

2.在ORM年表的史前时代,我们需要将我们的对象模型转化为一条一条的SQL语句,通过直连或是DB helper在关系数据库构造我们的数据库体系。而现在,基本上所有的ORM框架都提供了通过对象模型构造关系数据库结构的功能。

peewee模块(轻量级python中的ORM)

1.安装peewee模块:

(Ps:首先安装好pip,才可以执行以下命令安装)
linux :sudo pip install peewee
windows:cmd 下 输入:pip install peewee

2.peewee代码实例:

数据库和表模型的准备:

# /usr/bin/python# encoding:utf-8from peewee import *from datetime import date# 新建数据库 dbdb = SqliteDatabase('people.db')#表格模型 Person:这是一个Model的概念class Person(Model):    #CharField 为抽象数据类型 相当于 varchar    name = CharField()    #DateField 相当于 date    birthday = DateField()    #BooleanField 相当于 bool    is_relative = BooleanField()    # 所用数据库为db    class Meta:        database = db#表格模型 Petclass Pet(Model):    #外连接的声明(和Person关联)    owner = ForeignKeyField(Person, related_name='pets')    name = CharField()    animal_type = CharField()    class Meta:        database = db#连接数据库dbdb.connect()

在db中建表Person和Pet:

db.create_tables([Person, Pet])

Person 和 Pet表数据操作:

# Storing Datauncle_bob = Person(name='Bob', birthday=date(1967, 1, 28), is_relative=True)uncle_bob.save()grandma = Person.create(name='Grandma', birthday=date(1935, 3, 1), is_relative=True)herb = Person.create(name='Herb', birthday=date(1950, 5, 1), is_relative=False)grandma.name = 'Marry'grandma.save()bob_kitty = Pet.create(owner=uncle_bob, name='Kitty', animal_type='cat')herb_fido = Pet.create(owner=herb, name='Fido', animal_type='dog')herb_mittens = Pet.create(owner=herb, name='Mittens', animal_type='cat')herb_mittens_jr = Pet.create(owner=herb, name='Mittens Jr', animal_type='cat')# return the value of delete_instance() is the number of rows removed form the database# delete Dataherb_mittens.delete_instance()  # he had a great life# Modify Dataherb_fido.owner = uncle_bobherb_fido.save()bob_fido = herb_fido  # rename our variable for clarity

Person,Pet—>Select 操作:

# Retrieving Data# 查询名字为Marry的persongrandma = Person.select().where(Person.name == 'Marry').get()#列出Person表中所有的personfor person in Person.select():    print person.name, person.is_relative#查询Pet表中animal_type为cat的所有petquery = (Pet         .select(Pet, Person)         .join(Person)         .where(Pet.animal_type == 'cat'))for pet in query:    print pet.name, pet.owner.name#查询Pet表中主人名为Bob的所有petfor pet in Pet.select().join(Person).where(Person.name == 'Bob'):    print pet.name#查询Pet表中person为uncle_bob的所有petfor pet in Pet.select().where(Pet.owner == uncle_bob):    print pet.name#查询Pet表中person为uncle_bob结果按pet名排列for pet in Pet.select().where(Pet.owner == uncle_bob).order_by(Pet.name):    print pet.name#将Person表中的person按生日降序查询for person in Person.select().order_by(Person.birthday.desc()):    print person.name, person.birthday#查询Person表中person所拥有的pet数量及名字和类型for person in Person.select():    print person.name, person.pets.count(), 'pets'    for pet in person.pets:        print '      ', pet.name, pet.animal_type#查询Person表中生日小于1940或大于1960的persond1940 = date(1940, 1, 1)d1960 = date(1960, 1, 1)query = (Person         .select()         .where((Person.birthday < d1940) | (Person.birthday > d1960)))#查询Person表中生日在1940和1960之间的personfor person in query:    print person.name, person.birthdayquery = (Person         .select()         .where((Person.birthday > d1940) & (Person.birthday < d1960)))for person in query:    print person.name, person.birthday#按照expression查询person名开头为小写或大写 G 的personexpression = (fn.Lower(fn.Substr(Person.name, 1, 1)) == 'g')for person in Person.select().where(expression):    print person.name

Person, Pet—>Update操作

q = User.update(active=False).where(User.registration_expired == True)q.execute() 

Person, Pet—>Insert操作

q = User.insert(username='admin', active=True, registration_expired=False)q.execute() 

Person, Pet—>Delete操作

q = User.delete().where(User.active == False)q.execute() 

关闭数据库

db.close()

总结

关于peewee还有很多具体的东西,我这里只罗列了一些基本的操作,开发过程中需要了解更多的内容,请参照peewee官方API,见:peeweeAPI

0 0
原创粉丝点击