简体   繁体   English

如何使属性函数像数据库中的真实字段一样工作

[英]how to make a property function to act like a real field in the database

i want to make a (group by) which depend on some other fields ,我想制作一个(分组依据),它依赖于其他一些领域,

models.py模型.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)

views.py视图.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:...)

is it possible to make the property function act as a field in the db ?是否可以使属性函数充当数据库中的字段? or if there another way to achieve the same thing i trying to implement ?或者是否有另一种方法可以实现我试图实现的相同目标? i also tried to views.py我也试过views.py

from .models.Order import total 

context['daily'] = 
Order.objects.values('date_time').aggregate(days=Sum(total()))

but doesnt work !但不起作用!

thanks for any advice ..感谢您的任何建议..

You can annotate your queryset.您可以注释您的查询集。 For example:例如:

Order.objects.annotate(
    _total=Sum(F('productorder__quantity') * F('productorder__product__price'))
)

You can then for example annotate per date_time value, like:例如,您可以对每个date_time值进行注释,例如:

Order.objects.values('date_time').annotate(
    _total=Sum(F('productorder__quantity') * F('productorder__product__price'))
).order_by('date_time')

If you want to do this per day, you can first make an annotation that extracts the day:如果你想每天都这样做,你可以先做一个提取当天的注释:

from django.db.models.functions import TruncDay

Order.objects.annotate(
    day=TruncDay('date_time')
).values('day').annotate(
    _total=Sum(F('productorder__quantity') * F('productorder__product__price'))
).order_by('day')

This is a QuerySet of dictionaries, that looks like:这是一个 QuerySet 字典,看起来像:

<QuerySet [
    {'day': datetime(2019, 1, 1), '_total': 123},
    {'day': datetime(2019, 1, 2), '_total': 456},
    {'day': datetime(2019, 1, 3), '_total': 789},
]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM