You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scores.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from django.db import connection, transaction
  2. from django.db.models import get_model
  3. ProductRecord = get_model('analytics', 'ProductRecord')
  4. Product = get_model('catalogue', 'Product')
  5. class Calculator(object):
  6. # Map of field name to weight
  7. weights = {'num_views': 1,
  8. 'num_basket_additions': 3,
  9. 'num_purchases': 5}
  10. def __init__(self, logger):
  11. self.logger = logger
  12. self.cursor = connection.cursor()
  13. def run(self):
  14. self.calculate_scores()
  15. self.update_product_models()
  16. def calculate_scores(self):
  17. self.logger.info("Calculating product scores")
  18. # Build the "SET ..." part of the SQL statement
  19. weighted_sum = " + ".join(
  20. ["%s*`%s`" % (weight, field) for field, weight
  21. in self.weights.items()])
  22. ctx = {'table': ProductRecord._meta.db_table,
  23. 'weighted_total': weighted_sum,
  24. 'total_weight': sum(self.weights.values())}
  25. sql = '''UPDATE `%(table)s`
  26. SET score = %(weighted_total)s / %(total_weight)s''' % ctx
  27. self.logger.debug(sql)
  28. self.cursor.execute(sql)
  29. transaction.commit_unless_managed()
  30. def update_product_models(self):
  31. self.logger.info("Updating product records")
  32. qs = ProductRecord.objects.all()
  33. for record in qs:
  34. record.product.score = record.score
  35. record.product.save()
  36. self.logger.info("Updated scores for %d products" % qs.count())