我想创建一个依赖于其他字段的(分组依据),
模型.py
class Product(models.Model):
pass
class Order(models.Model):
id = models.AutoField(primary_key = True)
products = models.ManyToManyField(Product ,through='ProductOrder')
date_time = models.DateTimeField(default=datetime.now())
@property
def total(self):
return self.productorder_set.aggregate(
price_sum=Sum(F('quantity') * F('product__price'),
output_field=IntegerField()) )['price_sum']
class ProductOrder(models.Model):
product = models.ForeignKey(Product,
on_delete=models.CASCADE,default='' )
ordering = models.ForeignKey(Order,
on_delete=models.CASCADE,blank=True,null=True)
quantity = models.IntegerField(default=1)
View .py
class View(ListView):
pass
def get_context_data(self , *args,**kwargs):
context = super().get_context_data(*args , **kwargs)
context['daily'] =
Order.objects.values('date_time').aggregate(days=Sum('total'))
return context
(Cannot resolve keyword 'total' into field. Choices are:...)
是否可以使属性函数充当数据库中的字段?或者是否有另一种方法可以实现我试图实现的相同目标? 我也尝试过 View .py
from .models.Order import total
context['daily'] =
Order.objects.values('date_time').aggregate(days=Sum(total()))
但不起作用!
感谢您的建议..
最佳答案
您可以注释您的查询集。例如:
Order.objects.annotate(
<b>_total=Sum(F('productorder__quantity') * F('productorder__product__price'))</b>
)
然后,您可以对每个 date_time
值进行注释,例如:
Order.objects.values('date_time').annotate(
_total=Sum(F('productorder__quantity') * F('productorder__product__price'))
).order_by('date_time')
如果你想每天都这样做,你可以先做一个提取日期的注释:
from django.db.models.functions import <b>TruncDay</b>
Order.objects.annotate(
<b>day=TruncDay('date_time')</b>
).values('day').annotate(
_total=Sum(F('productorder__quantity') * F('productorder__product__price'))
).order_by('day')
这是一个字典查询集,如下所示:
<QuerySet [
{'day': datetime(2019, 1, 1), '_total': 123},
{'day': datetime(2019, 1, 2), '_total': 456},
{'day': datetime(2019, 1, 3), '_total': 789},
]>
关于python - 如何使属性函数像数据库中的真实字段一样起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57713444/