Django:创建查询集?

时间:2019-06-20 15:20:00

标签: python django

我正在尝试获得以下结果<EventQuerySet [{4: 10000, 5: 20000, [...]}]>

“获取”方法有以下工作流程:

1)获取组织者的每个活动事件

def organizers(self):
    return self.request.user.organizers

Event.objects.filter(
    organizer__in=self.organizers,
    status=EventStatus.LIVE
)

2)对于每个事件>获取属于该特定事件的所有票证。特别是,我需要访问每张票的数量和价格

3)获取已经售出的门票数量

.annotate(
    sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))
)
.order_by('organizer')

4)现在,我们拥有计算每个事件的max_remaining_gross_sale所需的所有信息:

示例:

事件与pk 4

门票1:price_gross *(数量-sold_tickets)

门票2:price_gross *(数量-sold_tickets)

事件与pk 5

门票1:price_gross *(数量-sold_tickets)

[...]

5)从每个事件的所有门票中,我们得出总和,得出以下结果: <EventQuerySet [{4: 10000, 5: 20000, [...]}]>

我没有设法以5)的结果构建该QuerySet。您对我有什么建议吗?

以下是我的模型以及相关字段:

class Ticket(TimeStampedModel):
    quantity = models.PositiveIntegerField(
        verbose_name=_("Quantity"),
        validators=[MinValueValidator(1), MaxValueValidator(100_000)],
    )
    status = models.CharField(
        max_length=8,
        choices=TicketStatus.CHOICES,
        default=TicketStatus.ON_SALE,
        verbose_name=_("Status"),
    )
    price_gross = models.PositiveIntegerField(
        verbose_name=_("Price gross"), help_text=_("Includes tax if you set any.")
    )

class Event(TimeStampedModel):
    status = models.CharField(
        max_length=8,
        choices=EventStatus.CHOICES,
        default=EventStatus.LIVE,
        verbose_name=_("Status"),
    )
    organizer = models.ForeignKey(
        Organizer, on_delete=models.PROTECT, related_name='events'
    )

class Attendee(TimeStampedModel):
    ticket = models.ForeignKey(
        Ticket, on_delete=models.PROTECT, related_name='attendees'
    )  # PROTECT = don't allow to delete the ticket if an attendee exists
    event = models.ForeignKey(
        Event, on_delete=models.PROTECT, related_name='attendees'
    )
    canceled = models.BooleanField(default=False, verbose_name=_("Canceled"))

1 个答案:

答案 0 :(得分:0)

编辑:坚持这一点-我在取消取消时就忽略了您的过滤器

根据我建议的修改,我认为这应该可行: Event.objects.annotate(max_remaining_gross_sale=Sum(F('tickets__price_gross')*(F('tickets__quantity')-F('tickets__attendees')), output_field=FloatField())).values()