Django使用Case手动控制排序
手动控制排序使用 Django update方法,所有涉及的数据每一条都会执行一次SQL update语句,MySQL有case语句可将所有影响的数据进行一次性更改,查看Django文档支持case语句 https://docs.djangoproject.com/en/2.2/ref/models/conditional-expressions/ >>> a_month_ago = date.today() - timedelta(days=30) >>> a_year_ago = date.today() - timedelta(days=365) >>> # Update the account_type for each Client from the registration date >>> Client.objects.update( ... account_type=Case( ... When(registered_on__lte=a_year_ago, ... then=Value(Client.PLATINUM)), ... When(registered_on__lte=a_month_ago, ... then=Value(Client.GOLD)), ... default=Value(Client.REGULAR) ... ), ... ) >>>