1

I have two models that are not related, but I need to do inner join on date, example:

select * from _Money m inner join _Pay p on m.date = p.date


class _Money(models.Model):
    money = models.CharField(max_length=3)
    date = models.DateField(null=True, blank=True)
    value = models.DecimalField(max_digits=7, decimal_places=2)


class _Pay(models.Model):
    date = models.DateField(null=True, blank=True)
    value = models.IntegerField(null=True, blank=True)

how is the way correct to do it on django?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Oztro
  • 86
  • 1
  • 12

1 Answers1

2

You can use a raw query:

roles = _Money.objects.raw("""SELECT 
                                  * 
                              FROM
                                  _Money m 
                                  INNER JOIN _Pay p 
                                  ON m.date = p.date""")

Also see this similar topic:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I read that using query (sql) is not optimal in django, is it? – Oztro Jun 22 '14 at 03:10
  • @Mattisbmx django object model doesn't cover every case out there. As docs say: `When the model query APIs don’t go far enough, you can fall back to writing raw SQL.` – alecxe Jun 22 '14 at 03:11
  • @Mattisbmx and yes, you can also do this in two `filter()` calls, one for `_Money` and another one for `_Pay` but this would be 2 queries, not efficient. – alecxe Jun 22 '14 at 03:13