I am having problems reducing the number of queries for a particular view. This is pretty heavy, but I'm sure it can be reduced:
Profile: name = CharField() Officers: club= ManyToManyField(Club, related_name='officers') title= CharField() Club: name = CharField() members = ManyToManyField(Profile) Election: club = ForeignKey(Club) elected = ForeignKey(Profile) title= CharField() when = DateTimeField()
The clubs have members and officers (president, director of the tournament). People can be members of several clubs, etc ... Officers are elected in elections, the results of which are stored.
Given a player, how can I find out the last elected officer in each of the player clubs?
I currently have
clubs = Club.objects.filter(members=me).prefetch_related('officers') for c in clubs: officers = c.officers.all() most_recent = Elections.objects.filter(club=c).filter(elected__in=officers).order_by('-when')[:1].get() print(c.name + ' elected ' + most_recent.name + ' most recently')
The problem is this looped request, itβs good and fast if you are in 1 club, but if you join fifty of my crawls in the database.
Edit: The response from Nil does what I want, but does not receive the object. I do not need an object, but I need another field, as well as time and date. If this is useful for a query:
Club.objects.annotate(last_election=Max('election__when'))
creates raw SQL
SELECT "organisation_club"."id", "organisation_club"."name", MAX("organisation_election"."when") AS "last_election" FROM "organisation_club" LEFT OUTER JOIN "organisation_election" ON ( "organisation_club"."id" = "organisation_election"."club_id" ) GROUP BY "organisation_club"."id", "organisation_club"."name"
I would really like the ORM answer, if at all possible (or the "mostly" ORM answer).