user = models.ForeignKey('users.user', on_delete=models.SET_NULL, null=True)
email = models.CharField(max_length=100, unique=True)
>>> star, flag = StarRating.objects.get_or_create(cafe_id=1, user_id=1)
>>> star
<StarRating: StarRating object (6)>
>>> flag
False
star, flag = StarRating.objects.get_or_create(cafe_id=cafe_id, user_id=user.id)
if not flag:
if star.score == data['score']:
star.delete()
return JsonResponse({'MESSAGE' : 'SCORE_DELETED'}, status=200)
else:
star.score = data['score']
star.save()
return JsonResponse({'MESSAGE' : 'SCORE_UPDATED'}, status=200)
else:
StarRating.objects.filter(cafe_id=cafe_id, user_id=user.id).update(score=data['score'])
return JsonResponse({'MESSAGE' : 'SCORE_CREATED'}, status=200)
comment_on_review = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
>>> star_ratings = StarRating.objects.values('cafe_id', 'score')
>>> star_ratings
<QuerySet [{'cafe_id': 1, 'score': Decimal('4.0')}, {'cafe_id': 1, 'score': Decimal('2.0')}, {'cafe_id': 1, 'score': Decimal('2.0')}, {'cafe_id': 2, 'score': Decimal('3.5')}, {'cafe_id': 3, 'score': Decimal('5.0')}, {'cafe_id': 3, 'score': Decimal('4.0')}, {'cafe_id': 10, 'score': Decimal('4.0')}, {'cafe_id': 8, 'score': Decimal('2.0')}, {'cafe_id': 1, 'score': Decimal('1.0')}, {'cafe_id': 2, 'score': Decimal('3.0')}, {'cafe_id': 2, 'score': Decimal('2.0')}, {'cafe_id': 2, 'score': Decimal('1.0')}]>
>>> from django.db.models import Avg
>>> cafe_avg_rating = star_ratings.values('cafe_id').annotate(avg_score=Avg('score'))
>>> cafe_avg_rating
<QuerySet [{'cafe_id': 1, 'avg_score': Decimal('2.25000')}, {'cafe_id': 2, 'avg_score': Decimal('2.37500')}, {'cafe_id': 3, 'avg_score': Decimal('4.50000')}, {'cafe_id': 8, 'avg_score': Decimal('2.00000')}, {'cafe_id': 10, 'avg_score': Decimal('4.00000')}]>
>>> cafe_ranking = cafe_avg_rating.order_by('-avg_score')
>>> cafe_ranking
<QuerySet [{'cafe_id': 3, 'avg_score': Decimal('4.50000')}, {'cafe_id': 10, 'avg_score': Decimal('4.00000')}, {'cafe_id': 2, 'avg_score': Decimal('2.37500')}, {'cafe_id': 1, 'avg_score': Decimal('2.25000')}, {'cafe_id': 8, 'avg_score': Decimal('2.00000')}]>
-
를 붙이면 반대로 정렬한다.>>> average_score = StarRating.objects.filter(cafe_id=1).aggregate(average=Avg('score'))
>>> average_score
{'average': Decimal('2.25000')}
>>> average_score['average']
Decimal('2.25000')
reviews = Review.objects.filter(cafe_id = cafe_id, comment_on_review_id__isnull = True)
>>> '{:.1f}원'.format(45000.000)
'45000.0원'
>>> '{:.0f}원'.format(45000.456)
'45000원'
<참고>