Как я могу найти, сколько 1 звезда/2 звезды----5star присутствует в процентах?

I've created a form for being stored ratings and feedback in the database. Ratings and Feedback are being stored in the database perfectly. But the problem is, I can't find out how many different types of rating stars are present in the database. How can I find out how many 1 star/2star/---5 stars are present in the object model in percentage? What should I do It?

models.py:

class Frontend_Rating(models.Model):
    USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating")
    Rating = models.IntegerField(null=True)
    Feedback = models.TextField(max_length=250, null=True)

    def __str__(self):
        return str(self.pk)+ str(".") + str(self.USer) + str("(") + str(self.Rating) + str("stars") +str(")")

Views.py:

def index(request):
    
    #rating____________________
    frontend_all_ratings = Frontend_Rating.objects.all()
    number_of_frontend_rating = frontend_all_ratings.count()
    average_rating = 0

    frontend_one_star = 0
    frontend_two_star = 0
    frontend_three_star = 0
    frontend_four_star = 0
    frontend_five_star = 0

    percentage_frontend_ONE_star = 0
    percentage_frontend_FIVE_star = 0


    for frontend_rating_item in frontend_all_ratings:
        frontend_rating = frontend_rating_item.Rating

        if frontend_rating:
            total_ratings = 0
            total_ratings += frontend_rating
            average_rating = round(total_ratings/frontend_all_ratings.count(),1)

        
    context = {
        "frontend_five_star":frontend_five_star,
        "frontend_one_star":frontend_one_star,
        "total_ratings":total_ratings,
        "average_rating":average_rating,
    }
    return render(request,'0_index.html',context)
number_of_frontend_rating = Frontend_Rating.objects.count()

# Divide value by overall count to get ratio and multiply ratio by 100 to get percentage
frontend_one_star = (Frontend_Rating.objects.filter(Rating=1).count() / overall_count)*100
frontend_two_star = (Frontend_Rating.objects.filter(Rating=2).count() / overall_count)*100
frontend_three_star = (Frontend_Rating.objects.filter(Rating=3).count() / overall_count)*100
frontend_four_star = (Frontend_Rating.objects.filter(Rating=4).count() / overall_count)*100
frontend_five_star = (Frontend_Rating.objects.filter(Rating=5).count() / overall_count)*100

Пожалуйста, поправьте меня, если я неправильно понял ваш вопрос

Вы можете получить данные с помощью одного запроса с:

from django.db.models import Avg, BooleanField, ExpressionWrapper, Q

data = Frontend_Rating.objects.aggregate(
    frontend_one_star=Avg(ExpressionWrapper(Q(Rating=1), output_field=BooleanField())),
    frontend_two_star=Avg(ExpressionWrapper(Q(Rating=2), output_field=BooleanField())),
    frontend_three_star=Avg(ExpressionWrapper(Q(Rating=3), output_field=BooleanField())),
    frontend_four_star=Avg(ExpressionWrapper(Q(Rating=4), output_field=BooleanField())),
    frontend_five_star=Avg(ExpressionWrapper(Q(Rating=5), output_field=BooleanField())),
)

frontend_one_star = data['frontend_one_star']
frontend_two_star = data['frontend_two_star']
frontend_three_star = data['frontend_three_star']
frontend_four_star = data['frontend_four_star']
frontend_five_star = data['frontend_five_star']

или для баз данных, использующих целочисленное деление, например :

from django.db.models import Count, FloatField, Q

data = Frontend_Rating.objects.aggregate(
    frontend_one_star=Count('pk', filter=Q(Rating=1), output_field=FloatField()) / Count('pk', output_field=FloatField()),
    frontend_two_star=Count('pk', filter=Q(Rating=2), output_field=FloatField()) / Count('pk', output_field=FloatField()),
    frontend_three_star=Count('pk', filter=Q(Rating=3), output_field=FloatField()) / Count('pk', output_field=FloatField()),
    frontend_four_star=Count('pk', filter=Q(Rating=4), output_field=FloatField()) / Count('pk', output_field=FloatField()),
    frontend_five_star=Count('pk', filter=Q(Rating=5), output_field=FloatField()) / Count('pk', output_field=FloatField()),
)

frontend_one_star = data['frontend_one_star']
frontend_two_star = data['frontend_two_star']
frontend_three_star = data['frontend_three_star']
frontend_four_star = data['frontend_four_star']
frontend_five_star = data['frontend_five_star']

Примечание: Модели в Django пишутся в PascalCase, а не snake_case, поэтому вы можете переименовать модель из Frontend_Rating в FrontendRating.


Примечание: обычно имена полей в модели Django записываются в snake_case, а не PascalCase, поэтому должно быть: rating вместо Rating.

Вернуться на верх