MBer1998
MBer1998

Reputation: 31

How to count values of many field for one object in Django?

Actually I'm stuck with one thing. I'm learning a lot but I need your help...

Django Models

from django.db import models

# Create your models here.

class Car(models.Model):
    mark = models.CharField(max_length=180)
    model = models.CharField(max_length=180, unique=True)

    def __str__(self):
        return "Car mark : {} Car model {}".format(self.id,self.model)
    

class Rate(models.Model):
    class Ratings(models.IntegerChoices):
        One = 1 
        Two = 2
        Three = 3
        Four = 4
        Five = 5
    
    grade = models.IntegerField(choices=Ratings.choices)
    car = models.ForeignKey(Car, on_delete=models.CASCADE,blank=True, null=True, related_name='rates')

First of all - I would like to get avg value of rates assigned to one object. Secondly, I would like to count how many rates each object has.

Upvotes: 0

Views: 147

Answers (2)

ruddra
ruddra

Reputation: 51978

Simple, try like this:

from django.db.models import Avg, Count

Car.objects.annotate(rate_count=Count('rates'), avg_rate=Avg('rates__grade')).values()

More information can be found on documentation

Upvotes: 3

mic4ael
mic4ael

Reputation: 8300

I am not an expert in Django but having looked at the models I would expect something like the following to work

number_of_rates = len(car.rates)
average = sum([rate.grade for rate in car.rates]) / len(car.rates)

Upvotes: 0

Related Questions