【问题标题】:How do I write this query in Django如何在 Django 中编写此查询
【发布时间】:2017-04-25 18:50:11
【问题描述】:

我将如何在 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)
        )

【问题讨论】:

    标签: mysql django python-3.x


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多