utils.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from django.db.models import Count
  2. from review.models import Review
  3. def get_review_count_by_month(location_id):
  4. sql = f'''
  5. SELECT review_id, MONTHNAME(create_time) as month, COUNT(review_id) as total_review
  6. FROM review_review
  7. WHERE DATE_ADD(CURRENT_TIMESTAMP(),INTERVAL -1 YEAR) <= create_time and location_id={location_id}
  8. GROUP BY MONTH(create_time)
  9. ORDER BY DATE(create_time) DESC
  10. '''
  11. qs = Review.objects.raw(sql)
  12. label = [q.month for q in qs]
  13. total_review = [q.total_review for q in qs]
  14. star_ratings = []
  15. for i in range(1, 6):
  16. sql = f'''
  17. SELECT review_id, MONTHNAME(create_time) as month, COUNT(review_id) as total_ratings
  18. FROM review_review
  19. WHERE DATE_ADD(CURRENT_TIMESTAMP(),INTERVAL -1 YEAR) <= create_time
  20. and location_id={location_id} and star_rating={i}
  21. GROUP BY MONTH(create_time)
  22. ORDER BY DATE(create_time) DESC
  23. '''
  24. qs = Review.objects.raw(sql)
  25. ratings = [0]*len(label)
  26. for q in qs:
  27. ratings[label.index(q.month)] = q.total_ratings
  28. star_ratings.append(ratings)
  29. response = {
  30. 'month': label,
  31. 'total_reviews': total_review,
  32. 'one_star': star_ratings[0],
  33. 'two_star': star_ratings[1],
  34. 'three_star': star_ratings[2],
  35. 'four_star': star_ratings[3],
  36. 'five_star': star_ratings[4]
  37. }
  38. return response
  39. def get_review_count_by_month_all():
  40. sql = f'''
  41. SELECT review_id, MONTHNAME(create_time) as month, COUNT(review_id) as total_review
  42. FROM review_review
  43. GROUP BY MONTH(create_time)
  44. ORDER BY DATE(create_time) DESC
  45. '''
  46. qs = Review.objects.raw(sql)
  47. label = [q.month for q in qs]
  48. total_review = [q.total_review for q in qs]
  49. star_ratings = []
  50. for i in range(1, 6):
  51. sql = f'''
  52. SELECT review_id, MONTHNAME(create_time) as month, COUNT(review_id) as total_ratings
  53. FROM review_review
  54. WHERE star_rating={i}
  55. GROUP BY MONTH(create_time)
  56. ORDER BY DATE(create_time) DESC
  57. '''
  58. qs = Review.objects.raw(sql)
  59. ratings = [0]*len(label)
  60. for q in qs:
  61. ratings[label.index(q.month)] = q.total_ratings
  62. star_ratings.append(ratings)
  63. response = {
  64. 'month': label,
  65. 'total_reviews': total_review,
  66. 'one_star': star_ratings[0],
  67. 'two_star': star_ratings[1],
  68. 'three_star': star_ratings[2],
  69. 'four_star': star_ratings[3],
  70. 'five_star': star_ratings[4]
  71. }
  72. return response