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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM