Home > Mobile >  How Can I get Sum Total of Django Model Column through a Queryset
How Can I get Sum Total of Django Model Column through a Queryset

Time:08-07

I am working on an Event App where I want to get the Total Amount of Pin Tickets that has been activated and I don't know how to do it.

Below is what I have tried and I am getting this error: 'QuerySet' object has no attribute 'ticket'

Here are my Models

class Ticket(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    price = models.PositiveIntegerField()
    category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False)
    added_date = models.DateField(auto_now_add=True)

    def __str__(self):
        return f"{self.event} "

    #Prepare the url path for the Model
    def get_absolute_url(self):
        return reverse("ticket-detail", args=[str(self.id)])

    def generate_pin():
        return ''.join(str(randint(0, 9)) for _ in range(6))

class Pin(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
    value = models.CharField(max_length=6, default=generate_pin, blank=True)
    added = models.DateTimeField(auto_now_add=True,  blank=False)
    reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
    status = models.CharField(max_length=30, default='Not Activated')

    #Save Reference Number
    def save(self, *args, **kwargs):
         self.reference == str(uuid.uuid4())
         super().save(*args, **kwargs) 

    def __unicode__(self):
        return self.ticket

    class Meta:
        unique_together = ["ticket", "value"]

    def __str__(self):
         return f"{self.ticket}"

    def get_absolute_url(self):
        return reverse("pin-detail", args=[str(self.id)])

Here is my Views.py

from django.db.models import Count, Sum
def profile(request):    
    amount_sold_pins = Pin.objects.filter(status='Activated')
    total_sold_tickets = amount_sold_pins.ticket.price
    total = total_sold_tickets.aggregate(total = 
    Sum('price')).get('total') or 0

context = {
    'guest':reservations,
    'total':total,
}

return render(request, 'user/profile.html', context)

Someone should please help with the best way of getting my Pin Tickets that are activated. Thanks

CodePudding user response:

To get the total price of tickets with pin status activated, use this.

Ticket.objects.filter(pin__status="Activated").aggregate(
    total=Sum('price')
)['total']

If is just how many tickets has a pin status activated.

Ticket.objects.filter(pin__status="Activated").count()

The error you are seen is because amount_sold_pins is a queryset.

amount_sold_pins = Pin.objects.filter(status='Activated')
# amount_sold_pins is a queryset of Pin
total_sold_tickets = amount_sold_pins.ticket.price # the queryset dosen't have a ticket field, the Pins has.
  • Related