F/Q查询 |
测试表
from django.db import models # Create your models here. class MyCharField(models.Field): def __init__(self,max_length,*args,**kwargs): self.max_length = max_length super().__init__(max_length=max_length,*args,**kwargs) def db_type(self, connection): return ‘char(%s)‘%self.max_length class Product(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) # 改字段可以为空 choices = ((1,‘男‘),(2,‘女‘),(3,‘其他‘)) gender = models.IntegerField(choices=choices,default=2)
F查询
res = models.Product.objects.filter(maichu__gt=F(‘kucun‘)) print(res) 将所有的商品的价格提高100块 models.Product.objects.update(price=F(‘price‘)+100) 将所有商品的名字后面都加一个爆款 from django.db.models.functions import Concat from django.db.models import Value models.Product.objects.update(name=Concat(F(‘name‘),Value(‘爆款‘)))
Q查询
res = models.Product.objects.filter(price=188.88,name=‘连衣裙爆款‘) print(res) from django.db.models import F, Q res = models.Product.objects.filter(Q(price=188.88),Q(name=‘连衣裙爆款‘)) # and res = models.Product.objects.filter(Q(price=188.88)|Q(name=‘连衣裙爆款‘)) # or res = models.Product.objects.filter(Q(price=188.88)|~Q(name=‘连衣裙爆款‘)) # not 混合使用 需要注意的是Q对象必须放在普通的过滤条件前面 res = models.Product.objects.filter(~Q(name=‘连衣裙爆款‘),price=188.88) # not print(res) Q对象补充(******) from django.db.models import F, Q q = Q() q.connector = ‘or‘ # 通过这个参数可以将Q对象默认的and关系变成or q.children.append((‘price‘,188.88)) q.children.append((‘name‘,‘高跟鞋爆款‘)) res = models.Product.objects.filter(q) # Q对象查询默认也是and print(res)
事务 |
事务的ACID
from django.db import transaction from django.db.models import F with 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(‘hahah‘)
only 与 defer |
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) res = models.Product.objects.filter(id=1).first() print(res.gender) print(res.get_gender_display()) # 获取编号对应的中文注释 models.Product.objects.create(...gender=1)
原文:https://www.cnblogs.com/guanchao/p/11017041.html