Lets take this models:
class Computer(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
cpu = models.PositiveIntegerField(null=False, blank=False)
ram = models.PositiveBigIntegerField(null=False, blank=False)
customer = models.ForeignKey(
Customer,
related_name='Computers',
on_delete=models.SET_NULL,
null=True,
blank=True
)
class Disk(models.Model):
computer = models.ForeignKey(
Computer,
related_name='Disks',
on_delete=models.CASCADE,
null=False,
blank=False
)
size = models.PositiveBigIntegerField(null=False, blank=False)
class Customer(models.Model):
name = models.CharField(max_length=255,
blank=True, null=True)
creation_date = models.DateTimeField(auto_now_add=True)
enabled = models.BooleanField(
blank=False, null=False, default=False)
I want list, by customer, the total number of CPU, RAM, and disk size (with the number of computer for each customer).
something like this:
{'customer': ACME_Corp., 'cpu__sum': 72, 'ram__sum': 10737418240, 'computer__sum': 10, 'disks__sum': 10000000000000}
I tried something like that:
Computer.values('customer').annotate(Sum('cpu'), Sum('ram'), Sum('Disks__size'),computer__sum=Count('computer_id'))
The problem is: If a computer has multiple Disk, I am going to add his cpu (RAM and count) as many time as his number of disk
for example if we have 2 computers with 1 cpu each, but one of them has two disks attached, the cpu total will not be 2, but 3...
Any help will be appreciated, thank you !!