Django ORM的F查询和Q查询实例
表结构
Django中Models模块创建表
from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=32) price = models.DecimalField(max_digits=6, decimal_places=2) # 库存数 kucun = models.IntegerField() # 卖出数 maichu = models.IntegerField() def __str__(self): return "{} 价格:{} 库存:{} 卖出:{}".format(self.name, self.price, self.kucun, self.maichu)
查询实例
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app01.settings") import django django.setup() from app01 import models from django.db.models import F,Q,Value # F查询实例 # 查询出卖出数大于库存数的商品 # ret = models.Product.objects.filter(maichu__gt=F('kucun')) # print(ret) # 将每个商品的价格提高50块 # models.Product.objects.update(price = F('price')-50) # 将所有商品的名称后面加一个 '新款' from django.db.models.functions import Concat from django.db.models import Value # models.Product.objects.update(name=Concat(F('name'),Value('新款'))) # 卖出数大于100 并且 价格小于100块的 # ret = models.Product.objects.filter(maichu__gt=100,price__lt=100) # print(ret) from django.db.models import Q # Q查询实例 # 查询 卖出数大于100 或者 价格小于100块的 # ret = models.Product.objects.filter(Q(maichu__lt=100)|Q(price__gt=100)) # print(ret) # 查询 库存数是100 并且 卖出数不是0 的产品 # ret = models.Product.objects.filter(Q(kucun=100) & ~Q(maichu=0)) # print(ret) # 查询产品名包含新款, 并且库存数大于60的 # ret = models.Product.objects.filter(Q(name__contains='新款') & Q(kucun__gt=60)) # print(ret)
Ideal are like the stars --- we never reach them ,but like mariners , we chart our course by them