【发布时间】:2021-11-15 17:16:24
【问题描述】:
我有三个模型:
class BaseModel(Model):
deleted = BooleanField(default=False)
class Document(BaseModel):
def total_price()
return DocumentLine.objects.filter(
section__in=self.sections.filter(deleted=False),
deleted=False,
).total_price()
class Section(BaseModel):
document = ForeignKey(Document, on_delete=CASCADE, related_name='sections')
class LineQuerySet(QuerySet):
def with_total_price(self):
total_price = F('quantity') * F('price')
return self.annotate(
total_price=ExpressionWrapper(total_price, output_field=DecimalField())
)
def total_price(self):
return self.with_total_prices().aggregate(
Sum('total_price', output_field=DecimalField())
)['total_price__sum'] or Decimal(0.0)
class Line(BaseModel):
objects = LineQuerySet.as_manager()
section = ForeignKey(Section, on_delete=CASCADE, related_name='lines')
price = DecimalField()
quantity = DecimalField()
正如您在LineQuerySet 上看到的那样,有一种方法可以根据价格和数量用每行的总价格注释查询集。
现在我可以通过这样的方式轻松获得整个文档的总价格(注意带有deleted=True 的行和部分会被忽略):
document = Document.objects.get(pk=1)
total_price = document.total_price()
但是,现在我想生成一个包含多个文档的查询集,并使用每个文档的 total price 对其进行注释。我尝试了注释、聚合、使用 prefetch_related(使用 Prefetch)和 OuterRef 的组合,但我似乎无法在不引发错误的情况下获得我想要的结果。
是否有某种方法可以在查询集中执行此操作,从而可以通过此 total_price 字段进行过滤或排序?
【问题讨论】: