django-aggregation


Display Django values() on Foreign Key in template as object instead of its id

我的梦境 提交于 2020-01-12 14:24:09
问题 I have a queryset in Django that calls Model.objects.values('item') ... where 'item' is a Foreign Key. class Words(models.Model): word = models.CharField() class Frequency(models.Model): word = models.ForeignKey(Words) ... So this returns the item id and displays as an id in the template. How do I show the actual item value in the template instead of the id? 回答1: To refer properties of Foreign Key items, you should use '__' lookup notation in fields. MyModel.objects.values('item__prop1',

sort django queryset by latest instance of a subset of related model

安稳与你 提交于 2019-12-31 02:59:28
问题 I have an Order model and order_event model. Each order_event has a foreignkey to order. so from an order instance i can get: myorder.order_event_set . I want to get a list of all orders but i want them to be sorted by the date of the last event. A statement like this works to sort by the latest event date: queryset = Order.objects.all().annotate( latest_event_date=Max('order_event__event_datetime') ).order_by('latest_event_date') However, what I really need is a list of all orders sorted by

Django - Can you use property as the field in an aggregation function?

久未见 提交于 2019-12-29 05:47:08
问题 I know the short answer because I tried it. Is there any way to accomplish this though (even if only on account of a hack)? class Ticket(models.Model): account = modelfields.AccountField() uuid = models.CharField(max_length=36, unique=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] @property def repair_cost(self): # cost is a @property of LineItem(models.Model) return self.lineitem_set.aggregate(models.Sum('cost')) 回答1: No. Anything that goes through

Django: get aggregated value of two multiplied columns

非 Y 不嫁゛ 提交于 2019-12-20 23:26:08
问题 I need to get aggregated value of two columns. So first multiple them together and then get theirs sum() . Code below naturally does not work, it is just for clarification. Is it somehow possible or should I use raw SQL? SomeModel.objects .filter(**something) .aggregate(Sum('one_column' * 'another_col')) 回答1: You don't need that much raw SQL using extra(). obj = SomeModel.objects.filter(**something).extra( select = {'total': 'SUM(one_column * another_column)'}, ) 回答2: As I answered here https

Django ORM, sum of multiple columns

萝らか妹 提交于 2019-12-18 07:21:09
问题 I have a question about how we can filter by SUM of multiple columns. Example: class Foo(models.Model): i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() And I need to filter objects where SUM of i1, i2, i3 is less then 200. I've tried achive it with: Foo.objects.agregate(i_sum=Sum(i1,i2,i3)).filter(i_sum__lt=200) # error Foo.objects.agregate(i_sum=Sum([i1,i2,i3])).filter(i_sum__lt=200) # error Thanks. 回答1: You can use F(), and with annotation: Foo.objects

Django ORM, sum of multiple columns

邮差的信 提交于 2019-12-18 07:20:09
问题 I have a question about how we can filter by SUM of multiple columns. Example: class Foo(models.Model): i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() And I need to filter objects where SUM of i1, i2, i3 is less then 200. I've tried achive it with: Foo.objects.agregate(i_sum=Sum(i1,i2,i3)).filter(i_sum__lt=200) # error Foo.objects.agregate(i_sum=Sum([i1,i2,i3])).filter(i_sum__lt=200) # error Thanks. 回答1: You can use F(), and with annotation: Foo.objects

How to filter objects for count annotation in Django?

旧时模样 提交于 2019-12-17 10:08:04
问题 Consider simple Django models Event and Participant : class Event(models.Model): title = models.CharField(max_length=100) class Participant(models.Model): event = models.ForeignKey(Event, db_index=True) is_paid = models.BooleanField(default=False, db_index=True) It's easy to annotate events query with total number of participants: events = Event.objects.all().annotate(participants=models.Count('participant')) How to annotate with count of participants filtered by is_paid=True ? I need to

Django 1.11 Annotating a Subquery Aggregate

允我心安 提交于 2019-12-17 08:22:07
问题 This is a bleeding-edge feature that I'm currently skewered upon and quickly bleeding out. I want to annotate a subquery-aggregate onto an existing queryset. Doing this before 1.11 either meant custom SQL or hammering the database. Here's the documentation for this, and the example from it: from django.db.models import OuterRef, Subquery, Sum comments = Comment.objects.filter(post=OuterRef('pk')).values('post') total_comments = comments.annotate(total=Sum('length')).values('total') Post

Django: Group by date (day, month, year)

醉酒当歌 提交于 2019-12-17 01:39:42
问题 I've got a simple Model like this: class Order(models.Model): created = model.DateTimeField(auto_now_add=True) total = models.IntegerField() # monetary value And I want to output a month-by-month breakdown of: How many sales there were in a month ( COUNT ) The combined value ( SUM ) I'm not sure what the best way to attack this is. I've seen some fairly scary-looking extra-select queries but my simple mind is telling me I might be better off just iterating numbers, starting from an arbitrary

Can we do arithmetic using Django Subqueries?

本小妞迷上赌 提交于 2019-12-13 20:18:46
问题 I am wondering if Django's ORM allows us to do aggregate operations on subqueires, and then do arithmetic with the resulting values. What would be the proper way to go about something like this: record = PackingRecord.objects.filter(product=OuterRef('pk')) packed = FifoLink.objects.filter(packing_record__product=OuterRef('pk')) output = obj_set.annotate( in_stock=(Subquery(record.aggregate(Sum('qty'))) - Subquery(packed.aggregate(Sum('sale__qty')))) ).values('id', 'name', 'in_stock') 回答1: You

工具导航Map