django-aggregation

django: time range based aggregate query

本秂侑毒 提交于 2019-12-03 09:02:48
I have the following models, Art and ArtScore: class Art(models.Model): title = models.CharField() class ArtScore(models.Model): art = models.ForeignKey(Art) date = models.DateField(auto_now_add = True) amount = models.IntegerField() Certain user actions results in an ArtScore entry, for instance whenever you click 'I like this art', I save a certain amount of ArtScore for that Art. Now I'm trying to show a page for 'most popular this week', so I need a query aggregating only ArtScore amounts for that time range. I built the below query but it's flawed... popular = Art.objects.filter( artscore

Django: get aggregated value of two multiplied columns

假装没事ソ 提交于 2019-12-03 08:11:37
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')) You don't need that much raw SQL using extra() . obj = SomeModel.objects.filter(**something).extra( select = {'total': 'SUM(one_column * another_column)'}, ) Antstud As I answered here https://stackoverflow.com/a/36024089/4614802 the correct solution depends on django version. For django < 1.8

Get daily counts of objects from Django

假如想象 提交于 2019-12-03 01:09:01
I have a Django model with a created timestamp and I'd like to get the counts of objects created on each day. I was hoping to use the aggregation functionality in Django but I can't figure out how to solve my problem with it. Assuming that doesn't work I can always fall back to just getting all of the dates with values_list but I'd prefer to give the work to Django or the DB. How would you do it? Yuji 'Tomita' Tomita Alex pointed to the right answer in the comment: Count number of records by date in Django Credit goes to ara818 Guidoism.objects.extra({'created':"date(created)"}).values(

Django aggregation in templates?

喜欢而已 提交于 2019-12-02 17:56:08
问题 I'm thinking a bit about the concept of Django aggregates. I don't quite "get" how they can be used in my case. Basically i have a three-tier hierarchy of objects in my model, and the lowest object (Bar) contain values I want to aggregate. class Bar(models.Model): amount = models.FloatField() class Foo(models.Model): bars = models.ManyToManyField(Bar) class MyUser(models.Model): foos = models.ManyToManyField(Foo) I want my template to do the equivalent of this: {% for user in users %} <h2>{{

Django aggregation in templates?

时光总嘲笑我的痴心妄想 提交于 2019-12-02 10:34:44
I'm thinking a bit about the concept of Django aggregates. I don't quite "get" how they can be used in my case. Basically i have a three-tier hierarchy of objects in my model, and the lowest object (Bar) contain values I want to aggregate. class Bar(models.Model): amount = models.FloatField() class Foo(models.Model): bars = models.ManyToManyField(Bar) class MyUser(models.Model): foos = models.ManyToManyField(Foo) I want my template to do the equivalent of this: {% for user in users %} <h2>{{ user }}</h2> <table> <tr> <td>Foo</td>< <td>Average bar amount</td> </tr> {% for foo in user.foos.all %

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

南笙酒味 提交于 2019-12-02 01:16:31
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 latest date of A SUBSET OF EVENTS. For example my events are categorized into "scheduling", "processing

Django ORM, sum of multiple columns

柔情痞子 提交于 2019-11-29 12:36:16
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. You can use F() , and with annotation : Foo.objects.annotate(i_sum=F('i1') + F('i2')+ F('i3')).filter(i_sum=200) You can use extra Foo.objects.extra(where=["i1 +

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

▼魔方 西西 提交于 2019-11-29 05:32:22
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')) No. Anything that goes through a built-in manager has to be a real field, since they only touch the database. In order to work with a

Django order_by() filter with distinct()

孤人 提交于 2019-11-29 02:11:07
问题 How can I make an order_by like this .... p = Product.objects.filter(vendornumber='403516006')\ .order_by('-created').distinct('vendor__name') The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor .. Hope it makes sense? I got this DB error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("search_vendor"."name") "search_product"... 回答1: Based on your error message and this other

How to filter objects for count annotation in Django?

不问归期 提交于 2019-11-27 16:53:28
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 query all events regardless of number of participants, e.g. I don't need to filter by annotated result. If