Bharat Bittu
Bharat Bittu

Reputation: 525

How do we get multiple values from a single django orm query?

class Test(ModelBase):
     team = models.IntegerField(null=True)



id    created_at                           team
 1     2018-02-14 10:33:46.307214+05:30    1
 2     2018-02-24 10:41:40.307681+05:30    1
 3     2018-03-14 12:00:02.748088+05:30    1
 4     2018-03-12 18:05:33.598297+05:30    3
 5     2018-03-12 18:04:00.694774+05:30    3
 6     2018-04-14 11:24:48.554993+05:30    3
 7     2018-04-14 11:42:27.442441+05:30    3
 8     2018-05-11 15:53:21.528813+05:30    3
 9     2018-05-08 15:49:58.684201+05:30    3

How can we get from a single query current month & team = 3 count, last month & team = 3 count?

Upvotes: 0

Views: 2129

Answers (3)

seuling
seuling

Reputation: 2956

You just can filter with chain queryset. Just get your current_month and last_month (it should be integer) and

Test.objects.filter(created_at__month__in=[current_month, last_month], team=3)

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can use Q object which allows to perform query with OR conditions:

current_month = datetime.datetime.now().month
first_day_of_current_month = datetime.datetime.now().replace(day=1)
last_month = (first_day_of_current_month - datetime.timedelta(days=1)).month

Test.objects.filter(Q(created_at__month=current_month, team=3)|Q(created_at__month=last_month, team=3))

Upvotes: 1

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

You can use TruncMonth to get data filtered by each month. You can then gen first and last index value.

from django.db.models.functions import TruncMonth
from django.db.models import Sum

queryset = Test.objects.all().annotate(
             month=TruncMonth('created_at')).values('month').annotate(
             number=Sum('team'))

Upvotes: 0

Related Questions