I need to figure out how to translate MySQL query into Django (Python) language. Any help? Basically I need to get the total from each table plus the remain total after spend.
class Trip(models.Model):
name = models.CharField('Name', max_length=254)
class Account(models.Model):
name = models.CharField('Name', max_length=254)
class Wallet(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
incoming_date = models.DateField(verbose_name='Incoming Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
class Expense(models.Model):
trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT)
outcome_date = models.DateField(verbose_name='Outcome Date')
total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True)
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
SELECT *, (wallet_total - expense_total) AS remain_total
FROM (
SELECT account.name, SUM(wallet.total) AS wallet_total
FROM account
INNER JOIN wallet
ON wallet.account_id = account.id
WHERE wallet.trip_id=4
GROUP BY account.name
) AS wallet,
(
SELECT account.name, SUM(expense.total) AS expense_total
FROM account
INNER JOIN expense
ON expense.account_id = account.id
WHERE expense.trip_id=4
GROUP BY account.name
) AS expense;
2
Answers
Template
If you want an explanation, comment below ^_^