Wednesday, September 5, 2018

Django Nested Query with Aggregate.Sum()


QUESTION

I have an application that will make on-line reservations for a series of weekly events. I would like to display the list of upcoming events in an html template with the number of remaining seats available in a single html page. I was able to create views to display the list of upcoming events and another view to display the number of remaining seats available but I am unable to figure out how to nest the two into a single view. Example below...

HTML OUTPUT

Event Title Week 1 - x amount of seats remaining for this event

Event Title Week 2 - x amount of seats remainign for this event

Event Title Week 3 - x amount of seats remaining for this event

and so on ....

MODELS

class Events(models.Model):
   event_date = models.DateField(auto_now_add=False)
   event_time = models.TimeField(auto_now_add=False)
   event_type = models.CharField(max_length=20, choices=EVENT_TYPE)
   seating = models.IntegerField(default=0)
   title = models.CharField(max_length=200)
   description = models.TextField()
   menu = models.TextField()
   price = models.DecimalField(max_digits=6, decimal_places=2)
   publish = models.CharField(max_length=1, choices=PUBLISH_CHOICE)

   def __int__(self):
      return self.title

class Reservations(models.Model):
   user_id = models.IntegerField(default=0)
   event_id = models.IntegerField(default=0)
   reservations = models.IntegerField(default=0)

   def __int__(self):
      return self.event


VIEWS

def events_view(request):
    events=Events.objects.filter(publish='Y').filter(event_date__gte=datetime.now()).order_by('event_date') reservation_count = Reservations.objects.aggregate(Sum('reservations'))
 
    return render(request, 'restaurant/events.html',{"events":events, "reservation_count":reservation_count, })

def make_reservation_view(request, pk):
   event = Events.objects.get(id=pk)
   seating_available = Events.objects.get(id=pk)
   seating_available = seating_available.seating
   reservation_count = Reservations.objects.filter(event_id=pk).aggregate(res_sum=Sum('reservations'))
   res = reservation_count['res_sum']
   seats_remaining = seating_available - res

   return render(request, 'restaurant/make_reservation.html', {"event":event, \
                                                           "seats_remaining":seats_remaining,})


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/735e8874-e41b-40c1-859d-263077ce6c9f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment