免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Python學(xué)習(xí)路線介紹Peewee怎么用

Python學(xué)習(xí)路線介紹Peewee怎么用,SQLAlchemy 功能很強大,文檔很豐富,是一個重量級的 ORM 框架。本文給大家介紹一個小清新,輕量級 ORM 框架 Peewee,支持 Python 2.7+ 和 3.4+,支持 SQLite、MySQL 以及 PostgreSQL。如果對 Django 的 ORM 比較熟悉,那么 Peewee 的學(xué)習(xí)成本會非常低。

安裝

pip install peewee

模型定義

from peewee import *db = SqliteDatabase('people.db')class BaseModel(Model):    class Meta:        database = dbclass Person(BaseModel):    name = CharField(verbose_name='姓名', max_length=10, null=False, index=True)    gender = IntegerField(verbose_name='姓別', null=False, default=1)    birthday = DateField(verbose_name='生日', null=True, default=None)    class Meta:        table_name = 'people'

首先定義了我們的模型類Person(用過 Django 的同學(xué)一定對這種模型定義方式十分熟悉,跟 Django 中模型的定義十分相似),使用 SqliteDatabase指定了使用的數(shù)據(jù)庫people.db。

然后定義了Person這個表的數(shù)據(jù)字段,如果不指定主鍵,peewee會自動幫我們創(chuàng)建一個id的字段作為主鍵。每一個Field都有幾個參數(shù)可以配置,長度的大小,是否為空(null)和默認(rèn)值(default),索引(index)和唯一索引(unique)幾個常見的數(shù)據(jù)庫選項。

創(chuàng)建數(shù)據(jù)庫表

Person.create_table()# 或db.create_tables([Person])

操作數(shù)據(jù)庫

  • 直接創(chuàng)建實例,然后調(diào)用實例方法save()。

  • 也可以通過create()類方法創(chuàng)建實例并保存。

p = Person(name='tom', gender=1, birthday=date(2000, 1, 1))p.save()jerry = Person.create(name='jerry', gender=0, birthday=date(1999, 12, 1))
  • 使用delete().where().execute()進行條件刪除,where()是刪除條件,execute()執(zhí)行刪除操作。

  • 如果是已經(jīng)查詢出來的實例對象,則調(diào)用實例方法delete_instance()進行刪除。

# 刪除姓名為 tom 的數(shù)據(jù)Person.delete().where(Person.name=='tom').execute()# 已經(jīng)實例化的對象, 調(diào)用 delete_instance() 進行刪除操作p = Person(name='tom', gender=1, birthday=date(2000, 1, 1))p.save()p.delete_instance()
  • 使用update().wahere().excute()進行條件更新。針對已經(jīng)查詢到的數(shù)據(jù)對象,在修改完對象屬性后,直接save()更新。

# 已經(jīng)實例化的對象,且擁有 id 這個 primary key,則修改屬性后,save 即是更新操作p = Person(name='tom', gender=1, birthday=date(2000, 1, 1))p.save()p.gender = 0p.save()# 更新 jerry 的 birthday 數(shù)據(jù)q = Person.update({Person.birthday: date(1999, 12, 12)}).where(Person.name=='jerry')q.execute()
  • 單條數(shù)據(jù)查詢使用Person.get(),也可以使用Person.select().where().get()。

  • 多條數(shù)據(jù)查詢使用Person.select().where()

# 查詢單條數(shù)據(jù)p = Person.select().where(Person.name=='tom').get()print(p.name, p.gender, p.birthday)# 使用簡寫 Model.get()p = Person.get(Person.name=='tom')print(p.name, p.gender, p.birthday)# 查詢多條數(shù)據(jù)people = Person.select().where(Person.gender==1)for p in people:    print(p.name, p.gender, p.birthday)
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
像對象一樣對待數(shù)據(jù)
Python 序列化模型數(shù)據(jù)為 JSON
Python namedtuple(命名元組)使用實例
Python筆記 class中的
Python的輕量級ORM框架peewee
Python編程:使用pythink查詢數(shù)據(jù)庫
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服