我试图在查询集中获取一个字段,该字段取决于注释的结果。我尝试在带注释的查询集上使用extra,这似乎不起作用。
让我们说我的模型看起来像这样:
class Foo(models.Model):
name = models.CharField(...)
class FooData(models.Model):
foo = models.ForeignKey(Foo)
sales = models.PositiveIntegerField()
items_sold = models.PositiveIntegerField()
我有一个Foo对象的查询集
some_foos = Foo.objects.filter()
我已经注释了它以获得FooData的总和。
some_foos.object.annotate(
total_sales=Sum("foodata__sales"),
total_items_sold=Sum("foodata__items_sold")
)
现在我想得到我想要使用的平均价格.extra。它们似乎不起作用。 (我查看了生成的sql查询)。
#Wont work, fields not defined yet.
some_foos.object.annotate(
total_sales=Sum("foodata__sales"),
total_items_sold=Sum("foodata__items_sold")
).extra(select={'price_avg': "total_sales/total_items_sold"})
#Wont work, this adds an extra clause in group by
price_avg = "SUM(appname_foodata.sales)/SUM(appname_foodata.items_sold)"
some_foos.object.annotate(
total_sales=Sum("foodata__sales"),
total_items_sold=Sum("foodata__items_sold")
)