F、Q查询,事务以及only与defer

在models视图中创建列表

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()

  def __str__(self)
    return '商品对象的名字:%s'%self.name

在MySQL中创建表

# 查询卖出数大于50的商品

res = models.Product.objects.filter(maichu__get=50)
print(res)

#查询卖出数大于库存数的商品。

这个时候就要用到拿到所有的卖出数,库存数,没有具体的条件,现在就要用到F与Q查询

F查询

F:能够帮助获取到某一个字段对应的值

from django.db.models inport F,Q

res = models.Product.objects.filter(maichu__gt=F('kucun'))
print(res)

# 将所有商品的价格提高100块(这句话说的就是增删改查中的改数据,首先要拿到原价格,再在原来的价格上加100)

models.Product.objects.update(price=F('price')+100)

# 将所有商品名称后面都加一个爆款(可能很多小伙伴都想到了用join去做字符串的拼接,但是Django是不支持这种格式的)

from django.db.models.functions import Concat
from django.db.models import Value

models.Product.objects.update(name=Concat(F('name'),Value('爆款')))

Q查询

为什么要用到Q查询?

因为在filter中条件都是and关系,这里想让里面的条件关系变成or,所以就用到了Q

from django.db.models inport F,Q
res = models.Product.objects.filter(Q(price=188.88),Q(name='l连衣裙爆款')) #and
res = models.Product.objects.filter(Q(price=188.88)|Q(name='l连衣裙爆款')) # or
res = models.Product.objects.filter(Q(price=188.88)|~Q(name='l连衣裙爆款'))  #not
print(res)

混合使用:

Q如果要和关键字条件混合使用,Q必须在前

res = models.Product.objects.filter(~Q(name='连衣裙爆款'),(price=188.88))
print(res)

字符串转成变量名的name

   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('hahaha')    

django自定义char类型

在models中定义类

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)  #该字段可以为空

再执行makemigrations    migrate

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)

猜你喜欢

转载自www.cnblogs.com/chengzige/p/11020580.html