获得预订的客人数量django

时间:2017-09-03 22:54:31

标签: python django

如果每个用户参加活动,他们都可以预订,但每个活动只有一定的空间。

我想在活动中表明剩下10个座位中有5个。 我似乎无法找到已预订状态为活动或待处理状态的客人总数。

这是我的活动模型

class Events(models.Model):

ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),)
ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing'))

user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.CharField(max_length=1, default='b', choices=ACTIVE)
title = models.CharField(max_length=50, blank=True, default='')
description = models.TextField(max_length=500, blank=True, default='')
date = models.DateField()
time = models.TimeField()
price = models.CharField(max_length=240, blank=True, default='')
seats = models.IntegerField()
alcohol_choice = models.CharField(max_length=1, default='n' ,choices=ALCOHOL)
starter = models.TextField(max_length=350, blank=True, default='')
main_menu = models.TextField(max_length=350, blank=True, default='')
dessert = models.TextField(max_length=350, blank=True, default='')
notes = models.TextField(max_length=350, blank=True, default='')
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)

@property
def bookings_total(self):
    return self.user.bookings_set.filter(bookingstatus='y').count()

这是我的预订模式

class Bookings(models.Model):

OPTIONS_STATUS = (('y', "Yes"), ('n', "No"), ('p', "Pending"),)

user = models.ForeignKey(User, on_delete=models.CASCADE)
event = models.ForeignKey(Events, on_delete=models.CASCADE)
eventdate = models.DateField()
event_amount = models.CharField(max_length=50, blank=True, default='')
guests = models.IntegerField()
bookingstatus = models.CharField(max_length=50, default='p', blank=True, choices=OPTIONS_STATUS)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)

这是我的观点代码

 today = datetime.now().strftime('%Y-%m-%d')

 events_list_data = Events.objects.filter(active='a').filter(Q(date__gte=today)|Q(date=today)).order_by('date')

这是我的模板代码

 {% for event_list in events_list_data %}
    -- CODE GOES HERE --
    {{ event_list.bookings_total }} Seats Left
 {% endfor %} 

2 个答案:

答案 0 :(得分:1)

<强>尝试:

 events = Events.objects.filter(active='a').\
 filter(Q(date__gte=today)|Q(date=today)).order_by('date')

 events = events.filter(Q(booking__bookingstatus='n')|Q(booking__bookingstatus='p'))
 events = events.annotate(num_of_seats=Count('booking'))

现在您可以使用.num_of_seats来显示活动中没有席位。

在html文件中:

{% for event in events %}
      {{event.title}}
      {{even.num_of_seats}}
{% endfor %}

答案 1 :(得分:1)

如果我正确理解,你可以尝试

@property
def bookings_total(self):
    return self.bookings_set.filter(bookingstatus='y').count()

@property
def bookings_left(self):
    return self.bookings_total - self.seats