Etsè FIATSI
Etsè FIATSI

Reputation: 27

List of arrivals, per year

I have these three models (I've summarize them):

class Tourist(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class Etablissement(models.Model):    
    name = models.CharField(max_length=30)

class Arrival(models.Model):
    tourist = models.ForeignKey(Tourist, on_delete=models.CASCADE)
    place = models.ForeignKey(Etablissement, on_delete=models.CASCADE)

I want, for a Tourist, to have all his arrivals, per year. I've tried this:

def detailTourist(request, id):
    touriste = Tourist.objects.get(id=id)
    datas = Arrival.objects.annotate(year=TruncYear('arrival_date')).values('year').annotate(total=Arrival.objects.filter(tourist=touriste)).order_by()

but it give me an error: sub-select returns 19 columns - expected 1 (the arrival model has 19 field so i guest that's why it says 19.

So finnaly, how can I do it please ?

Upvotes: 1

Views: 31

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can use itertools.groupby(…) [Python-doc] to group the items, given it is already ordered by year:

from itertools import groupby
from operator import attrgetter


def detailTourist(request, id):
    datas = Arrival.objects.annotate(year=TruncYear('arrival_date')).order_by('year')
    datas = { y: list(vs) for y, vs in groupby(datas, attrgetter('year')) }
    # …

Here it will create a dictionary that maps a year to a list of Arrival objects.

Upvotes: 0

Related Questions