Last active
January 22, 2020 10:07
-
-
Save GaretJax/153a0abad68fb42e8d2735b7fccf7a6a to your computer and use it in GitHub Desktop.
Django-CMS fix-tree optimization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cms.models import CMSPlugin | |
from cms.utils.plugins import reorder_plugins | |
from django.db import connection, transaction | |
from django.db.models import Count, F | |
from treebeard.mp_tree import sql_length | |
def new_fix_tree(): | |
print("RUNNING PATCHED CMSPLUGIN FIX TREE") | |
vendor = CMSPlugin.get_database_vendor('write') | |
cursor = CMSPlugin._get_database_cursor('write') | |
sql = ( | |
"UPDATE %s " | |
"SET depth=" + sql_length("path", vendor=vendor) + "/%%s " | |
"WHERE depth!=" + sql_length("path", vendor=vendor) + "/%%s" | |
) % (connection.ops.quote_name(CMSPlugin._meta.db_table),) | |
vals = [CMSPlugin.steplen, CMSPlugin.steplen] | |
with transaction.atomic(): | |
cursor.execute(sql, vals) | |
# Numchild | |
with transaction.atomic(): | |
bad_plugins = ( | |
CMSPlugin.objects.annotate(real=Count('cmsplugin')) | |
.exclude(numchild=F('real')) | |
.values_list('pk', 'real') | |
) | |
for pk, numchild in bad_plugins: | |
CMSPlugin.objects.filter(pk=pk).update(numchild=numchild) | |
with transaction.atomic(): | |
ids = CMSPlugin.objects.raw( | |
"""select distinct t1.parent_id as id | |
from cms_cmsplugin as t1 | |
inner join cms_cmsplugin as t2 | |
on t1.parent_id = t2.parent_id and t1.position = t2.position and t1.id < t2.id""" | |
) | |
ids = (plugin.pk for plugin in ids) | |
for parent in CMSPlugin.objects.filter(pk__in=ids).select_related( | |
'placeholder' | |
): | |
order = ( | |
CMSPlugin.objects.filter(parent_id=parent.pk) | |
.order_by('position', 'path') | |
.values_list('pk', flat=True) | |
) | |
reorder_plugins( | |
parent.placeholder, parent.pk, parent.language, order | |
) | |
CMSPlugin.fix_tree = new_fix_tree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment