Агрегация с использованием отношений и __last в Django

Мне нужно выяснить, как отфильтровать количество новых покупателей в определенном магазине, отфильтрованное по дням. Я попробовал несколько агрегаций, но ни одна не сработала.

Смотрите код ниже

# query all orders in a specific store by day (simplified)
orders = Order.objects.filter(created_at_gte=today, created_at_lt=tomorrow, store=store)

# filter all unique customers

customers = []

for order in orders:

    if not order.customer in customers:
        customers.append(order.customer)


# iterate all customers, looking for the oldest order for each one in that store and count as a new client if this oldest order is between the dates being looked up

new_customers = 0

for customer in customers:

    oldest_order = customer.orders.filter(store=store).prefetch_related('store').last()
    is_new = (tomorrow > oldest_order.created_at > today)
    
    if is_new:
        new_customers += 1

print(new_customers)

Однако этот код занимает слишком много времени из-за итерации в:

oldest_order = customer.orders.filter(store=store).prefetch_related('store').last()

Я думаю, что что-то вроде нижеприведенного будет работать, но "__last" здесь не работает.

Order.objects.filter(store=store, created_at__gte=today, created_at__lt=tomorrow).annotate(Count('customer__orders__last', distinct=True))

Спасибо!

Вернуться на верх