标签: django-aggregation

如何注释 Django JSONField (对象数组)数据的总和?

我有这样的模型

# models.py
class MyModel( models.Model ):
    orders = models.JsonField(null= True, blank=True, default=list)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)

我在这个结构中存储了 json 数据。

[
    {
        "order_name": "first order",
        "price": 200
    },
    {
        "order_name": "second order",
        "price": 800
    },
    {
        "order_name": "third order",
        "price": 100
    }
]
Run Code Online (Sandbox Code Playgroud)

我想计算所有 json 对象的价格总和,即 200+800+100

django django-aggregation django-postgresql django-jsonfield django-3.0

7
推荐指数
1
解决办法
2559
查看次数

Django-“ WhereNode”对象没有属性“ output_field”错误

我正在尝试查询和注释模型中的一些数据:

class Feed(models.Model):     # Feed of content
    user = models.ForeignKey(User, on_delete=models.CASCADE)

class Piece(models.Model):    # Piece of content (video or playlist)
    removed = models.BooleanField(default=False)
    feed    = models.ForeignKey(Feed, on_delete=models.CASCADE)
    user    = models.ForeignKey(User, on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)

在以下查询中未使用其他字段,因此在此跳过了它们。

在我看来,我需要获取经过身份验证的用户的所有供稿的queryset。批注应包含所有未删除的数量。

最初,Piece模型不包含removed字段,并且一切都可以与queryset一起运行,如下所示:

Feed.objects.filter(user=self.request.user).annotate(Count('piece'))
Run Code Online (Sandbox Code Playgroud)

但是随后我将字段添加removedPiece模型中,只需要计算未删除的部分

Feed.objects.filter(user=self.request.user)
            .annotate(Count('piece'), filter=Q(piece__removed=False))
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误:

'WhereNode' object has no attribute 'output_field'
Run Code Online (Sandbox Code Playgroud)

这只是django在错误页面上输出的内容的一小部分,因此,如果这还不够的话,请告诉我我需要在问题中包含的内容。

我试图在这里和那里包含output_field诸如models.IntegerField()models.FloatField()(正确导入)之类的选项,但是出现了一些我未在此处提供的错误,因为我认为这些操作没有意义。

我正在使用Django 2.0.3

django django-models django-aggregation django-annotate django-2.0

6
推荐指数
1
解决办法
1756
查看次数

Django包含零的总和

我正在研究Django时间表应用程序,并且无法确定如何包含等于零的总和.如果我这样做:

entries = TimeEntry.objects.all().values("user__username").annotate(Sum("hours"))
Run Code Online (Sandbox Code Playgroud)

我得到所有有时间条目及其总和的用户.

[{'username': u'bob' 'hours__sum':49}, {'username': u'jane' 'hours__sum':10}]
Run Code Online (Sandbox Code Playgroud)

当我在某一天过滤掉它:

filtered_entries = entries.filter(date="2010-05-17")
Run Code Online (Sandbox Code Playgroud)

任何没有输入当天时间的人都被排除在外.有没有办法将那些总和为0的用户包括在内?

谢谢

django django-aggregation

5
推荐指数
1
解决办法
332
查看次数

Django ORM中多个到多个字段的复杂计数

所以我有一组可以出现在许多类别中的任务:

class TaskGroup(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200)
    icon = models.CharField(max_length=200, blank=True, null=True)

    def __unicode__(self):
        return unicode(self.name)


class Task(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()
    is_date_fuzzy = models.BooleanField()
    name = models.CharField(max_length=200)
    assignee = models.ForeignKey(User, verbose_name="users who is assigned the task", blank=True, null=True)
    task_groups = models.ManyToManyField(TaskGroup)
Run Code Online (Sandbox Code Playgroud)

如您所见,每个任务都可以出现在多个任务组中.

我希望我的查询满足以下条件:

  1. 应返回所有TaskGroup的列表.
  2. 特定组中任务数量的计数.即家具(3),床上用品(2),落地灯(6)
  3. 如果特定TaskGroup没有任务,则该组应该为0
  4. 每个组中的任务仅限于当前用户.

到目前为止我提出的最好的是这样的:

TaskGroup.objects.filter(
    task__assignee=current_usr
).annotate(
    task_count=Count('task__id')
).order_by('name')
Run Code Online (Sandbox Code Playgroud)

但它在进行计数之前会过滤掉所有内容,因此我看不到任务组的任务为零.

也许我正在思考但是我已经尝试过这么多年了,我现在正处于试图循环并自己做计算的时候.

我真的希望你能帮我节省一点我的理智!

sql django django-models django-aggregation

5
推荐指数
1
解决办法
395
查看次数

Django - 使用 get_FOO_display 进行聚合

考虑以下:

status = queryset.values('status').annotate(count=Count('status'))
Run Code Online (Sandbox Code Playgroud)

其中statusfield 是CharFieldwith choices。这将产生一个包含status数据库值及其计数的字典列表。

有没有办法聚合status并显示其显示值?我已经查找了我可能可以模拟的代码_get_FIELD_display,但重复框架的内部代码感觉有点黑客。

django django-orm django-aggregation

5
推荐指数
1
解决办法
1884
查看次数

Django ORM:过滤日期时间字段的时间增量

我试图根据两个DateTimeFields的时间差来获取帖子,例如,在发布后不到 10 分钟内删除的帖子。

class Post(models.Model):
    ...
    time_posted = models.DateTimeField()
    time_deleted = models.DateTimeField(blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

有了上面的模型,我试过了;

from datetime import timedelta

Post.objects.exclude(deleted__isnull=True).annotate(
    delta=F('time_deleted') - F('time_posted')
).filter(delta__lt=timedelta(minutes=10))
Run Code Online (Sandbox Code Playgroud)

并得到了一个TypeError: expected string or buffer. 然后我认为这可能是类型的变化(DateTime 对象产生 Time 对象)所以我尝试了ExpressionWrapper

Post.objects.exclude(deleted__isnull=True).annotate(
    delta=models.ExpressionWrapper(
        F('time_deleted') - F('time_posted'), 
        output_field=models.TimeField())
    ).filter(delta__gt=timedelta(minutes=10))
Run Code Online (Sandbox Code Playgroud)

但这也导致了同样的异常。

任何帮助深表感谢。

编辑

根据@ivan 的建议,我DurationField()改为尝试。我不再遇到异常,但 delta 总是0.

>>> post = Post.objects.exclude(deleted__isnull=True).annotate(
        delta=ExpressionWrapper(F('deleted') - F('time'), 
        output_field=DurationField())
    ).first()
>>> post.time_posted
datetime.datetime(2015, 8, 24, 13, 26, 50, 857326, tzinfo=<UTC>)
>>> post.time_deleted
datetime.datetime(2015, 8, 24, …
Run Code Online (Sandbox Code Playgroud)

django django-orm django-aggregation

5
推荐指数
1
解决办法
2023
查看次数

django 使用基于查询的聚合值注释模型

假设我有以下模型结构:

Parent():

Child():
parent = ForeignKey(Parent)

GrandChild():
child = ForeignKey(Child)
state = BooleanField()
num = FloatField()
Run Code Online (Sandbox Code Playgroud)

我正在尝试从 ParentViewSet恢复以下内容:

  1. 孩子的数量。
  2. 'state' 为 True 时的 'num' 字段的总和。

我可以执行以下操作:

queryset = Parent.objects\
    .annotate(child_count=Count('child'))\
    .annotate(sum_total=Sum('child__grandchild__num'))
Run Code Online (Sandbox Code Playgroud)

这给了我 (1) 但不是 (2) 它给了我所有孙子的总和。如何在确保所有Parent对象仍在 QuerySet 中的同时适当地过滤孙子?

django django-models django-queryset django-aggregation django-annotate

5
推荐指数
2
解决办法
4725
查看次数

是否可以分别对多个列进行 GROUP BY 并使用 django ORM 通过其他列聚合它们中的每一个?

我知道如何GROUP BY汇总:

>>> from expenses.models import Expense
>>> from django.db.models import Sum
>>> qs = Expense.objects.order_by().values("is_fixed").annotate(is_fixed_total=Sum("price"))
>>> qs
<ExpenseQueryset [{'is_fixed': False, 'is_fixed_total': Decimal('1121.74000000000')}, {'is_fixed': True, 'is_fixed_total': Decimal('813.880000000000')}]>
Run Code Online (Sandbox Code Playgroud)

但是,如果我想对其他两列做同样的事情,它只返回最后一个:

>>> qs = (
...     Expense.objects.order_by()
...     .values("is_fixed")
...     .annotate(is_fixed_total=Sum("price"))
...     .values("source")
...     .annotate(source_total=Sum("price"))
...     .values("category")
...     .annotate(category_total=Sum("price"))
... )
>>> qs
<ExpenseQueryset [{'category': 'FOOD', 'category_total': Decimal('33.9000000000000')}, {'category': 'GIFT', 'category_total': Decimal('628')}, {'category': 'HOUSE', 'category_total': Decimal('813.880000000000')}, {'category': 'OTHER', 'category_total': Decimal('307')}, {'category': 'RECREATION', 'category_total': Decimal('100')}, {'category': 'SUPERMARKET', 'category_total': Decimal('52.8400000000000')}]>
Run Code Online (Sandbox Code Playgroud)

可以只用一个查询而不是三个查询来完成我想要的吗?

预期结果:

<ExpenseQueryset …
Run Code Online (Sandbox Code Playgroud)

python django django-queryset django-aggregation

5
推荐指数
1
解决办法
197
查看次数

Django:执行复杂注释和聚合时出现问题

这是型号:

class Purchase(models.Model):
    date           = models.DateField(default=datetime.date.today,blank=False, null=True)
    total_purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

我想在特定的日期范围内执行一个月份的"total_purchase"计算,如果一个月内没有购买,则总购买量应该是上个月的购买价值.如果在两个月内购买,那么总购买量会增加那两个......

例:

假设用户给出的日期范围是从4月到11月.

如果4月份购买2800美元,8月份购买5000美元,10月份购买6000美元.

然后输出将是这样的:

April      2800
May        2800
June       2800
July       2800
August     7800  #(2800 + 5000)
September  7800
October    13800 #(7800 + 6000)
November   13800
Run Code Online (Sandbox Code Playgroud)

知道如何在django查询中执行此操作吗?

谢谢

根据雷德尔米兰达先生的回答.我做了以下事情

import calendar
import collections
import dateutil

start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2019, 3, 31)

results = collections.OrderedDict()

result = Purchase.objects.filter(date__gte=start_date, date__lt=end_date).annotate(real_total = Case(When(Total_Purchase__isnull=True, then=0),default=F('tal_Purchase')))

date_cursor = start_date

while date_cursor < end_date:
    month_partial_total = result.filter(date__month=date_cursor.month).agggate(partial_total=Sum('real_total'))['partial_total']

    results[date_cursor.month] = month_partial_total …
Run Code Online (Sandbox Code Playgroud)

django django-models django-aggregation django-annotate

4
推荐指数
1
解决办法
204
查看次数

Django:注释相关字段列表

我有一个公司和用户模型以及相关模型 CompanyRecruiter:

class CompanyRecruiter(models.Model):

    organization = models.ForeignKey(Company, related_name="company_recruiters")
    recruiter = models.ForeignKey(User, related_name="company_recruiters")
Run Code Online (Sandbox Code Playgroud)

我想注释作为招聘人员的用户的用户 ID 列表,以便公司稍后能够对其进行过滤:

Company.objects.annotate(some_stuff=some_other_stuff).values_list("user_ids", flat=True)
# [ [1, 2], [1, 56], [] ]
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用自定义聚合和子查询但没有成功。我用的是postgres。

django django-aggregation django-annotate django-subquery

4
推荐指数
1
解决办法
3363
查看次数