当前位置:网站首页>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

​(User.is_active == True) & (User.is_admin == True)​

| (pipe)

OR

(User.is_admin) | (User.is_superuser)

​~​

NOT (unary negation)

​~(User.username << ['foo', 'bar', 'baz'])​

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.



原网站

版权声明
本文为[Pengshiyu psy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011403430718.html