Home > Blockchain >  Django - Adding up values in an object's many to many field?
Django - Adding up values in an object's many to many field?

Time:02-16

I have 2 classes

class Service(models.Model):
    service_name = models.CharField(max_length=15, blank=False)
    service_time = models.IntegerField(blank=False)

class Appointment(models.Model):
    name = models.CharField(max_length=15)
    service_selected = models.ManytoManyField(Service, blank=True)
    total_time = models.IntegerField(null=True, blank=True)

What Im trying to do is that after a user has selected the services and created an appointment, each of the services' service_time will be added up to equal total_time

I know I have to use something along the lines of


#in class Appointment
def save(self, *args, **kwargs):
    self.total_time  = self.service_selected.service_time    #it needs to add up all of the service_time from each service selected but that's where Im lost
    
    super(Appointment, self).save(*args, **kwargs)

But I don't know how to get the service_time value from each of the service_name that were selected, or how to query for every service_selected chosen in that appointment's object so that I can add up those values.

edit: Had to change

total_time = models.IntegerField(blank=False)

to

total_time = models.IntegerField(blank=False, null=False, default=0)

for the answer to work

CodePudding user response:

You can do it as follows:

#in class Appointment
def save(self, *args, **kwargs):
    self.total_time  = Service.objects.all().aggregate(total_time=Sum('service_time'))['total_time']
# You will have to run a query to get the data and aggregate according to that. You may change the query according to your needs.
    super(Appointment, self).save(*args, **kwargs)
  • Related