python - 如何使属性函数像数据库中的真实字段一样起作用

标签 python django group-by

我想创建一个依赖于其他字段的(分组依据),

模型.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/

相关文章:

python - 在 django rest 中自定义序列化器输出

Mysql - 按大于或小于当前时间的日期对记录进行分组 now() mysql

sql - 当 COUNT(*) 为 NULL 时,在 GROUP BY 中返回 0

python - 将列表中的 'continuation' 项分组。在 itertools groupby key 函数中存储状态不好吗?

python - 在 Python 中写入 UTF-8 文件

javascript - 如何在 django 的 View 之间传递对象?

python - Pandas read_csv 加速

django - 在django settings.py中设置gunicorn worker 的数量

python - datetime.strptime 和 dateutil 解析之间的区别?

python - 如何向用户输出力量?