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)
... ),
... )
>>> Client.objects.values_list('name', 'account_type')
<QuerySet [('Jane Doe', 'G'), ('James Smith', 'R'), ('Jack Black', 'P')]>
根据示例编写自己的应用
增加新数据:
max_sort = Kol.objects.filter(channel_type_kol=kol_type).order_by('sort').last().sort
if sort > max_sort:
dif_value = max_sort + 1
elif 0 < sort < max_sort + 1:
Kol.objects.filter(channel_type_kol=kol_type).update(
sort=Case(
When(sort__gte=sort,
then=F('sort') + 1),
default=F('sort')
)
)
dif_value = sort
更改排序:
max_sort = Kol.objects.filter(channel_type_kol=channel_type).order_by('sort').last().sort
if 0 < new_sort < kol_info.sort:
Kol.objects.filter(channel_type_kol=channel_type).update(
sort=Case(
When(sort__range=[new_sort, kol_info.sort - 1],
then=F('sort') + 1),
default=F('sort')
)
)
kol_info.sort = new_sort
kol_info.save()
elif kol_info.sort < new_sort < max_sort + 1:
Kol.objects.filter(channel_type_kol=channel_type).update(
sort=Case(
When(sort__range=[kol_info.sort + 1, new_sort],
then=F('sort') - 1),
default=F('sort')
)
)
kol_info.sort = new_sort
kol_info.save()
删除一条数据:
info = Kol.objects.get(id=id)
Kol.objects.filter(channel_type_kol=info.channel_type_kol).update(
sort=Case(
When(sort__gt=info.sort,
then=F('sort') - 1),
default=F('sort')
)
)
info.delete()