Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
How do I write this query in Django

How would I write the following SQL query in Django.

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;

The way the models are structured are.

Account(model):
    id

AccountTransactions(model):
    creation_date
    account_core_id = Account

AccountNote(model):
    account_core_id = Account
    creation_date
    email_status
    email_template

The query works fine but I can't seem to figure out how to do write this in django. Reading about prefetch related, but I don't see how I do it, since there is no direct one to connection between note and transcation.

Update: SOLUTION

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)
        )
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use .raw() to write sql query.

queryset = AccountTransaction.objects.raw("Sql query here")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!