将 PostgreSQL 重写为 Django ORM

Rewrite PostgreSQL to Django ORM

如果可以将此 PostgreSQL 查询重写为没有原始 SQL 的 Django ORM,我自己尝试过但没有成功。

这是基金的模型

class Fund(models.Model):
    name = models.CharField(max_length=320, unique=True)
    fund_manager = models.CharField()
     .............. 

这是 NAV 的模型

class NAV(models.Model):
    price = models.DecimalField(max_digits=9, verbose_name=_('NAV'))
    date = models.DateField(verbose_name=_('date'))
    fund = models.ForeignKey('Fund', related_name='navs')
    created_date = models.DateTimeField(default=now)

这里是 sql 有效的查询,需要重写为 Django ORM

select * from finance_fund ORDER BY(
  (select price from finance_nav where date='2016-11-08' and fund_id=finance_fund.id) / 
  (select price from finance_nav where date='2016-11-07' and fund_id=finance_fund.id)
)

所以基本上我需要按外键向后关系的两个简单查询的除法结果排序

提前致谢!

仅限原始 SQL。尝试类似的东西:

qs = Fund.objects.annotate(x=RawSQL("""
    (select price from finance_nav where finance_fund.id=fund_id and date=%s limit 1) 
    / (select price from finance_nav where finance_fund.id=fund_id and date=%s limit 1)
    """,('2016-11-08', '2016-11-07'))).order_by('x')