0
\$\begingroup\$

I combine two query sets (available_tickets_by_event and sold_tickets_by_event. My end goal is to combine it in ticket_stats_by_event. I wonder if there is a more efficient way to combine these`?

print(available_tickets_by_event)

[{'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 1, 'organizer': 1, 'available_tickets': 1721}]

print(sold_tickets_by_event)

[{'pk': 4, 'organizer': 1, 'sold_tickets': 2}, {'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}]

print(ticket_stats_by_event)

{4: {'sold_tickets': 2, 'organizer': 1, 'available_tickets': 30}, 6: {'sold_tickets': 1, 'organizer': 1, 'available_tickets': 20}, 5: {'sold_tickets': 1, 'organizer': 1, 'available_tickets': 10}, 1: {'sold_tickets': 529, 'organizer': 1, 'available_tickets': 1721}}

Here is the full function:

@property
def sold_tickets(self):
    return (
        Event.objects.filter(organizer__in=self.organizers)
        .values('pk', 'organizer')
        .annotate(
            sold_tickets=Count('attendees', filter=Q(attendees__canceled=False))
        )
    )

@property
def available_tickets(self):
    return (
        Event.objects.filter(organizer__in=self.organizers)
        .values('pk', 'organizer')
        .annotate(available_tickets=Coalesce(Sum('tickets__quantity'), 0))
    )

def ticket_stats_by_event(self, organizer):
    sold_tickets_by_event = [
        x for x in self.sold_tickets if x['organizer'] == organizer.pk
    ]

    available_tickets_by_event = [
        x for x in self.available_tickets if x['organizer'] == organizer.pk
    ]

    ticket_stats_by_event = {
        x['pk']: {'sold_tickets': x['sold_tickets']}
        for x in sold_tickets_by_event
    }

    for item in available_tickets_by_event:
        pk = item.pop('pk')
        ticket_stats_by_event[pk].update(item)

    return ticket_stats_by_event
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.