我在下面有一些簡單的模型
class Stamping(models.Model):
created = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class Product(Stamping):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_product')
name = models.CharField(max_length=300, unique=True)
price = models.FloatField()
class GroupProductOrder(Stamping):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_product_orders')
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField()
class Order(Stamping):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders')
fulfilled = models.BooleanField(default=False)
products = models.ManyToManyField(GroupProductOrder, blank=True)
@property
def total_price(self):
cost = 0
for product in self.products.all():
cost = product.total_price
return cost
現在我想查詢資料庫并每月回傳一些詳細資訊。詳細資訊,例如每個月的總銷售額和每個月的銷售額總和。我試過使用 annotate 但它似乎無法在其中傳遞模型屬性。解決這個問題的最佳方法是什么?預期輸出的示例是{'month': 'October', 'count': 5, 'total': 15}
uj5u.com熱心網友回復:
您可以使用以下陳述句進行查詢和注釋:
from django.db.models import Sum, F, FloatField
from django.db.models.functions import ExtractMonth
output = (
Order.objects
.annotate(
month=ExtractMonth("created")
)
.values("month")
.annotate(
count=Sum("products__quantity"),
total=Sum(
F("products__quantity") * F("products__product__price"),
output_field=FloatField()
)
)
.order_by("month")
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343310.html
標籤:姜戈
