1

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 ?

1 Answers1

0

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    It gives me an error: ('operator.attrgetter' object is not iterable). And beside I do not understant what you've done. Can you add some comment in the code please (I'm new to django so...). Thanks – Etsè FIATSI Oct 28 '22 at 10:06
  • @EtsèFIATSI: sorry, the items should have been swapped in the `groupby`. – Willem Van Onsem Oct 28 '22 at 10:48