在models檢視中建立列表
class在mysql中建立表product(models.model)
name = models.charfield(max_length=32)
price = models.decimalfield(max_digits=8, decimal_places=2)
maichu =models.integerfield()
kucun = models.integerfield()
def __str__(self)
return '商品物件的名字:%s'%self.name
# 查詢賣出數大於50的商品
res = models.product.objects.filter(maichu__get=50)#查詢賣出數大於庫存數的商品。print(res)
這個時候就要用到拿到所有的賣出數,庫存數,沒有具體的條件,現在就要用到f與q查詢
f查詢
f:能夠幫助獲取到某乙個字段對應的值
from# 將所有商品的**提高100塊(這句話說的就是增刪改查中的改資料,首先要拿到原**,再在原來的**上加100)django.db.models inport f,q
res = models.product.objects.filter(maichu__gt=f('
kucun'))
print(res)
models.product.objects.update(price=f('# 將所有商品名稱後面都加乙個爆款(可能很多小夥伴都想到了用join去做字串的拼接,但是django是不支援這種格式的)price
')+100)
from django.db.models.functions importq查詢為什麼要用到q查詢?concat
from django.db.models import
value
models.product.objects.update(name=concat(f('
name
'),value('
爆款')))
因為在filter中條件都是and關係,這裡想讓裡面的條件關係變成or,所以就用到了q
from混合使用:django.db.models inport f,q
res = models.product.objects.filter(q(price=188.88),q(name='
l連衣裙爆款
')) #
andres = models.product.objects.filter(q(price=188.88)|q(name='
l連衣裙爆款
')) #
orres = models.product.objects.filter(q(price=188.88)|~q(name='
l連衣裙爆款
')) #
notprint(res)
q如果要和關鍵字條件混合使用,q必須在前
res = models.product.objects.filter(~q(name='字串轉成變數名的name連衣裙爆款
'),(price=188.88))
print(res)
from django.db.models import事務四大特性(acid):原子性,一致性,隔離性,永續性f, q
q =q()
q.connector = 'or'
#通過這個引數可以將q物件預設的and關係變成or
price
',188.88))
'name
','高跟鞋爆款'))
res = models.product.objects.filter(q) #
q物件查詢預設也是and
print(res)
from django.db importdjango自定義char型別在models中定義類transaction
from django.db.models import
fwith transaction.atomic():
在with**塊兒寫你的事務操作
models.product.objects.filter(id=1).update(kucun=f('
kucun
')-1)
models.product.objects.filter(id=1).update(maichu=f('
maichu
')+1)
寫其他**邏輯
print('
hahaha
')
classmycharfield(models.field):
def__init__(self,max_length,*args,**kwargs):
self.max_length =max_length
super().
__init__(max_length=max_length,*args,**kwargs)
defdb_type(self, connection):
return
'char(%s)
'%self.max_length
class再執行makemigrations migrateproduct(models.model)
name = models.charfield(max_length=32) #
都是類例項化出來的物件
price = models.decimalfield(max_digits=8, decimal_places=2)
maichu =models.integerfield()
kucun =models.integerfield()
info = mycharfield(max_length=32,null=true) #
該欄位可以為空
only與defer
#拿到的是乙個物件 兩者是相反的
res = models.product.objects.values('
name')
res = models.product.objects.only('
name')
res = models.product.objects.defer('
name')
for i in
res:
print(i.name)
Django之F Q查詢,事務,自定義char欄位
f查詢 from django.db.models import f,q 當查詢條件來自於資料庫的某個字段,這個時候就必須使用f 查詢賣出數大於庫存數的商品 res models.product.objects.filter maichu gt f kucun 將所有商品的 提高100塊 model...
MySql多表查詢 事務
1.準備sql 建立部門表 create table dept id intprimary keyauto increment,name varchar 20 建立員工表 create table emp id intprimary keyauto increment,name varchar 10...
mysql查詢事務和鎖
記錄原因 今天在乙個mysql更新語句的執行過程中,總是執行超時,後來查到原因是因為有乙個事務沒有關閉,導致那條記錄的查詢和更新都會執行超時 以下的sql語句可以查詢當前資料庫,有哪些事務,都鎖定哪些資源 select trx id as 事務id trx state as 事務狀態 trx req...