From 36e5fcf4c9bf3617176727585df9a9eaff7ba6d9 Mon Sep 17 00:00:00 2001 From: alawibaba Date: Thu, 28 May 2015 10:16:15 -0400 Subject: [PATCH] Make clean_history.py use the StudentHistoryModule django model. --- .../management/commands/clean_history.py | 39 +++++++------------ 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/lms/djangoapps/courseware/management/commands/clean_history.py b/lms/djangoapps/courseware/management/commands/clean_history.py index 6478c07568..788ac6e399 100644 --- a/lms/djangoapps/courseware/management/commands/clean_history.py +++ b/lms/djangoapps/courseware/management/commands/clean_history.py @@ -16,7 +16,9 @@ import time import traceback from django.core.management.base import NoArgsCommand -from django.db import connection +from django.db import transaction +from django.db.models import Max +from courseware.models import StudentModuleHistory class Command(NoArgsCommand): @@ -72,7 +74,7 @@ class StudentModuleHistoryCleaner(object): batch_size = batch_size or self.BATCH_SIZE - connection.enter_transaction_management() + transaction.enter_transaction_management() self.last_student_module_id = self.get_last_student_module_id() self.load_state() @@ -104,7 +106,7 @@ class StudentModuleHistoryCleaner(object): Commit the transaction. """ self.say("Committing") - connection.commit() + transaction.commit() def load_state(self): """ @@ -140,11 +142,8 @@ class StudentModuleHistoryCleaner(object): """ Return the id of the last student_module. """ - cursor = connection.cursor() - cursor.execute(""" - SELECT max(student_module_id) FROM courseware_studentmodulehistory - """) - last = cursor.fetchone()[0] + last = StudentModuleHistory.objects.all() \ + .aggregate(Max('student_module'))['student_module__max'] self.say("Last student_module_id is {}".format(last)) return last @@ -176,17 +175,11 @@ class StudentModuleHistoryCleaner(object): Return a list: [(id, created), ...], all the rows of history. """ - cursor = connection.cursor() - cursor.execute( - """ - SELECT id, created FROM courseware_studentmodulehistory - WHERE student_module_id = %s - ORDER BY created, id - """, - [student_module_id] - ) - history = cursor.fetchall() - return history + history = StudentModuleHistory.objects \ + .filter(student_module=student_module_id) \ + .order_by('created', 'id') + + return [(row.id, row.created) for row in history] def delete_history(self, ids_to_delete): """ @@ -196,13 +189,7 @@ class StudentModuleHistoryCleaner(object): """ assert ids_to_delete - cursor = connection.cursor() - cursor.execute( - """ - DELETE FROM courseware_studentmodulehistory - WHERE id IN ({ids}) - """.format(ids=",".join(str(i) for i in ids_to_delete)) - ) + StudentModuleHistory.objects.filter(id__in=ids_to_delete).delete() def clean_one_student_module(self, student_module_id): """Clean one StudentModule's-worth of history.