django中when case的用法

    技术2023-05-31  82

    转载自:https://blog.csdn.net/kuanggudejimo/article/details/103577257 官网地址:https://docs.djangoproject.com/en/2.2/ref/models/conditional-expressions/#when when case根据不同的条件修改数据:

    # -*- coding:utf-8 -*- from django.db import models from datetime import datetime from django.db.models import Case, When, Value, Q class Book(models.Model): book_id = models.BigAutoField('书籍ID', primary_key=True) book_name = models.CharField('书名', max_length=20, db_index=True, default='') update_time = models.DateTimeField('更新时间', default=datetime.now) # 不要使用auto_now=True create_time = models.DateTimeField('创建时间', auto_now_add=True) def __str__(self): return 'id: %s, book_name: %s, update_time: %s, create_time: %s' % (self.book_id, self.book_name, self.update_time, self.create_time) # 初始化数据 book_ids = list(range(1, 10)) books = [Book(book_id=book_id, book_name='the_book_name') for book_id in book_ids] Book.objects.bulk_create(books) # 单个过滤条件 whens = [When(book_id=book_id, then=Value('book_name_id_%s' % book_id)) for book_id in book_ids] books = Book.objects.filter(book_id__in=book_ids) # 使用条件过滤限定范围,提高效率 # Django源码中sql模板为'CASE %(cases)s ELSE %(default)s END',default参数默认值为None # 如果要使不满足Case条件的记录不被修改,设置default为字段名,如下所示,否则字段值会被修改为NULL books.update(book_name=Case(*whens, default='book_name'), update_time=datetime.now()) print(Book.objects.filter(book_id__in=book_ids).all()[:len(book_ids)]) # 多个过滤条件 when = When(Q(book_id__gte=5) & Q(update_time__lte=datetime(2019, 12, 12, 12, 12, 12)), then=Value('book_name_id_gte_5_&_update_time_lte_time')) books = Book.objects.filter(book_id__in=book_ids) # 使用条件过滤限定范围,提高效率 books.update(book_name=Case(when, default='book_name'), update_time=datetime.now()) print(Book.objects.filter(book_id__in=book_ids).all()[:len(book_ids)]) # 按照不同规则修改字段 when_one = When(book_id__gte=5, then=Value('book_name_id_gte_5')) # 规则一 when_tow = When(book_id__lte=3, then=Value('book_name_id_lte_3')) # 规则二 books = Book.objects.filter(book_id__in=book_ids) # 使用条件过滤限定范围,提高效率 books.update(book_name=Case(when_one, when_tow, default='book_name'), update_time=datetime.now()) print(Book.objects.filter(book_id__in=book_ids).all()[:len(book_ids)]) # 按照不同规则同时修改多个字段 when_one = When(book_id__gte=5, then=Value(datetime(2019, 12, 12, 12, 12, 12))) # 规则一 when_tow = When(book_id__lte=4, then=Value('book_name_id_lte_4')) # 规则二 books = Book.objects.filter(book_id__in=book_ids) # 使用条件过滤限定范围,提高效率 books.update(create_time=Case(when_one, default='create_time'), book_name=Case(when_tow, default='book_name'), update_time=datetime.now()) print(Book.objects.filter(book_id__in=book_ids).all()[:len(book_ids)]

    也可以用于filter中:

    whens = [When(classify=type, then=Value(parent))] query = Category.objects.filter(parent_id__isnull=False, parent__name=Case(*whens)).values('id', 'name')
    Processed: 0.018, SQL: 9