如何在Django中编写此查询

时间:2017-04-25 18:50:12

标签: mysql django python-3.x

如何在Django中编写以下SQL查询。

SELECT COUNT(*)
FROM accounts_transactions
LEFT JOIN accounts_notes
ON accounts_notes.accounts_core_id = accounts_transactions.accounts_core_id
WHERE email_status='clicked' AND email_template_id IS NOT NULL 
AND accounts_transactions.creation_date >= accounts_notes.creation_date
AND accounts_transactions.creation_date <= accounts_notes.creation_date + INTERVAL 7 DAY;

模型的结构方式是。

Account(model):
    id

AccountTransactions(model):
    creation_date
    account_core_id = Account

AccountNote(model):
    account_core_id = Account
    creation_date
    email_status
    email_template

查询工作正常,但我似乎无法弄清楚如何在django中写这个。阅读相关的预取,但我不知道我是怎么做的,因为在笔记和交易之间没有直接连接。

更新:解决方案

queryset = AccountTransaction.objects.filter(
            account__note__email_template__isnull=False,
            account__note__email_status='clicked',
            creation_time__gte=F('account__note__creation_time'),
            creation_time__lte=F(
                'account__note__creation_time') + timedelta(days=7)
        )

1 个答案:

答案 0 :(得分:0)

使用.raw()编写sql查询。

queryset = AccountTransaction.objects.raw("Sql query here")