Django 操作补充

一,F查询和Q查询

  1,F查询

    Django提供F()来做比较,F()的实例可以在查询中引用字段,来比较同一个model实例中的两个不同字段的值。

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

res = models.Product.objects.filter(maichu__gt=F('kucun'))# 取出kukun字段的数值来进行比较
print(res)

    将所有的商品的价格提高100块:

models.Product.objects.update(price=F('price')+100) # F()取出的数值可以进行运算

    将所有商品的名字后面都加一个爆款:

# 导入修改char类型所需要的模块
from django.db.models.functions import Concat
from django.db.models import Value
models.Product.objects.update(name=Concat(F('name'),Value('爆款')))

  2,Q查询

    filter()等方法中逗号中隔开的条件是与的关系。如果你需要执行更复杂的查询(例如or查询),你需要使用Q对象

    查询价格为188.88或者名字叫连衣裙爆款的商品:

res = models.Product.objects.filter(Q(price=188.88)|Q(name='连衣裙爆款'))  # or

    查询价格为188.88或者名字不叫连衣裙爆款的商品:

res = models.Product.objects.filter(Q(price=188.88)|~Q(name='连衣裙爆款'))  # or not

    查询价格为188.88并且名字不叫连衣裙爆款的商品:

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

     Q查询补充:

      查询价格是188.88或者名字叫高跟鞋爆款的商品(字符串查询)

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)

  

二,事务

  事物的定义:将多个sql语句操作变成原子性操作,要么同时成功,有一个失败则里面回滚到原来的状态,保证数据的完整性和一致性(NoSQL数据库对于事务则是部分支持)

  ps:事物的ACID指的是:A:原子性 C:一致性 I:隔离性 D:持久性

# 开启事务处理
from django.db import transaction
from django.db.models import F
    try:
        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)
    except Exception as e:
        print(e)

三,其他

res = models.Product.objects.only('name')
res = models.Product.objects.defer('name') # only与defer  拿到的是一个对象  两者是相反的
res = models.Product.objects.filter(id=1).first()
print(res.gender)
print(res.get_gender_display())  # 获取编号对应的中文注释

  

   

原文地址:https://www.cnblogs.com/ay742936292/p/11018769.html