当前位置:网站首页>Peewee module basic use -orm
Peewee module basic use -orm
2022-06-12 01:21:00 【Pengshiyu psy】
github: https://github.com/coleifer/peewee
Official documents : http://docs.peewee-orm.com/en/latest/index.html#
Defining models is similar to Django or SQLAlchemy
Logical operators
The operator | Meaning | Example |
| AND | |
| (pipe) | OR | (User.is_admin) | (User.is_superuser) |
| NOT (unary negation) | |
Expression conversion
Method Meaning
.in_(value) IN lookup (identical to <<).
.not_in(value) NOT IN lookup.
.is_null(is_null) IS NULL or IS NOT NULL. Accepts boolean param.
.contains(substr) Wild-card search for substring.
.startswith(prefix) Search for values beginning with prefix.
.endswith(suffix) Search for values ending with suffix.
.between(low, high) Search for values between low and high.
.regexp(exp) Regular expression match (case-sensitive).
.iregexp(exp) Regular expression match (case-insensitive).
.bin_and(value) Binary AND.
.bin_or(value) Binary OR.
.concat(other) Concatenate two strings or objects using ||.
.distinct() Mark column for DISTINCT selection.
.collate(collation) Specify column with the given collation.
.cast(type) Cast the value of the column to the given type.
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
in_(): IN
not_in(): NOT IN
regexp(): REGEXP
is_null(True/False): IS NULL or IS NOT NULL
contains(s): LIKE %s%
startswith(s): LIKE s%
endswith(s): LIKE %s
between(low, high): BETWEEN low AND high
concat(): ||
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
give an example :
SELECT * FROM user WHERE username not like "%admin%"
# ~(User.username.contains('admin'))
SELECT * FROM user WHERE LENGTH(username)>45
# fn.length(User.username) > 45
- 1.
- 2.
- 3.
- 4.
- 5.
Reference resources : http://docs.peewee-orm.com/en/latest/peewee/query_operators.html
call sql function
Use fn
query = (User
.select(User.username, fn.COUNT(Tweet.id).alias('ct'))
.join(Tweet, JOIN.LEFT_OUTER, on=(User.id == Tweet.user_id))
.group_by(User.username)
.order_by(fn.COUNT(Tweet.id).desc()))
- 1.
- 2.
- 3.
- 4.
- 5.
Reference resources : https://peewee.readthedocs.io/en/latest/peewee/api.html#fn
The following code refers to the official example
Sample code :
# —*— coding: utf-8 —*—
from peewee import *
import datetime
from chinesename import chinesename
# py2 Solve coding problems
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# Set up the database
db = SqliteDatabase("demo.db")
class BaseModel(Model):
class Meta:
database = db
# Define data table
class User(BaseModel):
name = CharField(unique=True)
def __str__(self):
return "[user] id: %d name: %s"%(self.id, self.name)
class Tweet(BaseModel):
user = ForeignKeyField(User, related_name ="tweets")
message = TextField()
created_date = DateTimeField(default=datetime.datetime.now)
is_published = BooleanField(default=True)
def __str__(self):
return "[tweet] id: %d name: %s" % (self.id, self.user.name)
# Create data table
db.connect()
db.create_tables([User, Tweet], safe=True)
db.close()
# Add data
def add_data():
cn = chinesename.ChineseName()
for i in range(100):
user = User(name=cn.getName())
user.save()
User.create(name=cn.getName())
Tweet.create(user=user, message="hello world")
# add_data()
print datetime.datetime.now()
print datetime.date.today()
# Inquire about
ret = User.get(User.name==" Shen from ")
if ret: print ret
usernames = [" Ma Niang ", " Shen from "]
users = User.select().where(User.name.in_(usernames))
for user in users:
print user
tweets = Tweet.select().where(Tweet.user.in_(users))
for tweet in tweets:
print tweet
tweets = Tweet.select().join(User).where(User.name.in_(usernames))
for tweet in tweets:
print tweet
count = (Tweet
.select()
.where(
(Tweet.created_date >= datetime.date.today())&
(Tweet.is_published == True))
.count())
print count
# Pagination page 3 (users 41-60)
users = User.select().order_by(User.name).paginate(3, 20)
for user in users:
print user
# to update
query = User.update(name=" Simon blow snow ").where(User.id==1)
query.execute()
# Delete
query = User.delete().where(User.id==2)
query.execute()
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
边栏推荐
- Go out with a stream
- One article to show you how to understand the harmonyos application on the shelves
- Module 8 - Design message queue MySQL table for storing message data
- Such a change in people's understanding of the industrial Internet is not achieved overnight
- System. Commandline option
- Matlab foundation 04 - detailed analysis of the use and complex application of colon operator ":"
- Lambda quick start
- Component introduction - large screen cloud minimalist user manual
- Industry competition analysis and investment scale research report of global and Chinese micro potato industry 2022-2028
- be based on. NETCORE development blog project starblog - (11) access statistics
猜你喜欢

写代码复现论文的几点建议!

Some suggestions on writing code to reproduce the paper!

LabVIEW Arduino electronic weighing system (project Part-1)
![Is interface automation difficult? Take you from 0 to 1 to get started with interface automation test [0 basic can also understand series]](/img/78/f36cdc53b94dc7da576d114a3eb2a6.png)
Is interface automation difficult? Take you from 0 to 1 to get started with interface automation test [0 basic can also understand series]

Yixin Huachen talks about how to do a good job in customer master data management

【项目实训】微信公众号模板消息推送

打造Flutter高性能富文本编辑器——渲染篇

Matlab 基础应用02 wind 股票数据介绍和使用案例:

100 deep learning cases | day 41: speech recognition - pytorch implementation

Building circuits on glass
随机推荐
Weekly CTF week 1: Amazing tapes
SQL exercise summary 3
Devops landing practice drip and pit stepping records - (1)
Inventory: more than 20 typical safety incidents occurred in February, with a loss of nearly $400million
Mise en œuvre de l'ombre de l'animation du Vertex de l'unit é
Investment analysis and prospect forecast report of wearable biosensor industry for global and Chinese medical monitoring 2022 ~ 2028
MP3 to Wav to Midi
Article 8: Design of multi-functional intelligent trunk following control system | undergraduate graduation project - [reply and Q & a record of design completion]
kmeans从0到1
Colorize Voronoi Diagram Template
Elegant throttling / de buffeting decorator under LAYA
2022-06-11: note that in this document, graph is not the meaning of adjacency matrix, but a bipartite graph. In the adjacency matrix with length N, there are n points. Matrix[i][j] represents the dist
博文推荐|BookKeeper - Apache Pulsar 高可用 / 强一致 / 低延迟的存储实现
C dynamically calls the static library generated by go
[project training] wechat official account to obtain user openid
100 deep learning cases | day 41: speech recognition - pytorch implementation
Analysis report on demand status and Prospect Forecast of global and Chinese remote control helicopter industry 2022-2028
一文get,最容易碰上的接口自动化测试问题汇总
Equipment encryption of industrial control security
Unity頂點動畫的陰影實現