Сложный запрос для расчета баланса пользователя

У меня есть следующая модель (упрощенная):

class CoinTransaction(models.Model):
    class TransactionTypes(Enum):
        purchase_of_coins = ('pu', 'Purchase of Coins')  # Will have a positive amount
        conversion_into_money = ('co', 'Conversion Into Money')  # Will have a negative amount
        earning = ('ea', 'Earning')  # Will have a positive amount
        expense = ('ex', 'Expense')  # Will have a negative amount

        @classmethod
        def get_value(cls, member):
            return cls[member].value[0]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions')
    amount = models.IntegerField()
    transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes])

Я хочу, чтобы запрос Django получил два значения, относящиеся к данному пользователю: earned_coins и other_coins, не сохраняя их значение в модели User. Запрос должен вычислить эти значения следующим образом:

earned_coins = 0
other_coins = 0

for transaction in CoinTransaction.objects.filter(user=user).order_by('creation_date'):
   amount = transaction.amount

   if transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('conversion_into_money'), CoinTransaction.TransactionTypes.get_value('earning')]:
      earned_coins = max(earned_coins + amount, 0)
   elif transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('purchase_of_coins'), CoinTransaction.TransactionTypes.get_value('expense')]:
      other_coins += amount
      
      if other_coins < 0:
         earned_coins = max(earned_coins + other_coins, 0)
         other_coins = 0

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

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