OuterRef 和 Subquery 不使用日期时间过滤器检索数据
OuterRef and Subquery not retrieving data with datetime filter
我有一个用例,我试图使用以下模型计算给定金额和历史价格的某些交易的总价值:
class Transaction(models.Model):
...
asset = models.ForeignKey('Asset', ...)
amount = models.FloatField()
date = models.DateTimeField()
...
class Price(models.Model):
...
asset = models.ForeignKey('Asset', ...)
price = models.FloatField()
date = models.DateTimeField()
...
我想做的是,它通过查询获取所有交易并通过子查询注释历史价格:
from django.db.models.expressions import Subquery, OuterRef
price_at_date = Price.objects.filter(
date=OuterRef('date'),
asset=OuterRef('asset')).values('price')
transactions = Transaction.objects.filter(...).annotate(hist_price=Subquery(price_at_date))
此 returns None 为 hist_price
。我怀疑这与日期时间不匹配(不同时间但相同日期)这一事实有关。我尝试用 date__date
替换 date
的任意组合,但这仍然不起作用,并且 hist_price
中的 returns None
。
知道如何通过 Django ORM / 查询获取同一日期(但不是时间)的历史价格吗?
谢谢!
我找到了下一个案例:
from django.db.models.expressions import Subquery, OuterRef
from django.db.models.functions import Cast
from django.db.models import DateField
price_at_date = Price.objects.filter(date__date=OuterRef('date_date'), asset=OuterRef('asset')).values('price')
transactions = Transaction.objects.filter(...).annotate(date_date=Cast('date', DateField())).annotate(hist_price=Subquery(price_at_date))
主要思想是用类似的 DateField(在 DateTimeField 附近)注释查询集并将其用于 OuterRef。
我有一个用例,我试图使用以下模型计算给定金额和历史价格的某些交易的总价值:
class Transaction(models.Model):
...
asset = models.ForeignKey('Asset', ...)
amount = models.FloatField()
date = models.DateTimeField()
...
class Price(models.Model):
...
asset = models.ForeignKey('Asset', ...)
price = models.FloatField()
date = models.DateTimeField()
...
我想做的是,它通过查询获取所有交易并通过子查询注释历史价格:
from django.db.models.expressions import Subquery, OuterRef
price_at_date = Price.objects.filter(
date=OuterRef('date'),
asset=OuterRef('asset')).values('price')
transactions = Transaction.objects.filter(...).annotate(hist_price=Subquery(price_at_date))
此 returns None 为 hist_price
。我怀疑这与日期时间不匹配(不同时间但相同日期)这一事实有关。我尝试用 date__date
替换 date
的任意组合,但这仍然不起作用,并且 hist_price
中的 returns None
。
知道如何通过 Django ORM / 查询获取同一日期(但不是时间)的历史价格吗?
谢谢!
我找到了下一个案例:
from django.db.models.expressions import Subquery, OuterRef
from django.db.models.functions import Cast
from django.db.models import DateField
price_at_date = Price.objects.filter(date__date=OuterRef('date_date'), asset=OuterRef('asset')).values('price')
transactions = Transaction.objects.filter(...).annotate(date_date=Cast('date', DateField())).annotate(hist_price=Subquery(price_at_date))
主要思想是用类似的 DateField(在 DateTimeField 附近)注释查询集并将其用于 OuterRef。