utils.py 2.7 KB

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