场景:models.py
#coding: utf8import datetimefrom django.db import modelsclass Order(models.Model): orderid = models.CharField(max_length=64, unique=True) desc = models.CharField(max_length=512) product = models.CharField(max_length=512, null=True) amount = models.IntegerField() userid = models.CharField(max_length=512, null=True) create_time = models.DateTimeField(db_index=True)
1 F() ---- 专门取对象中某列值的操作
1 from django.db.models import F2 from core.models import Order3 4 order = Order.objects.get(orderid='123456789')5 order.amount = F('amount') - 16 order.save()
对应SQL语句
UPDATE `core_order` SET ..., `amount` = `core_order`.`amount` - 1 WHERE `core_order`.`orderid` = '123456789'
2 Q() ---- 对对象的复杂查询
Q对象(django.db.models.Q)可以对关键字参数进行封装,从而更好地应用多个查询。可以组合使用 &(and),|(or),~(not)操作符,当一个操作符是用于两个Q的
Python代码:
Order.objects.get( Q(desc__startswith='Who'), Q(create_time=date(2016, 10, 2)) | Q(create_time=date(2016, 10, 6)))
对应的sql 语句
SELECT * from core_order WHERE desc LIKE 'Who%' AND (create_time = '2016-10-02' OR create_time = '2016-10-06')
复杂参数:
params = [] username = request.GET.get("username") isactive = request.GET.get("isblock") if username: params.append(models.Q(username__contains=username)) if isactive: params.append(models.Q(is_block=isactive)) data = get_page_list(Account.objects.filter(*params), page_no=page_no, page_size=12)