[Answered ]-Optimise two SQL queries and a list comprehension

1👍

You need this SQL query:

SELECT P.id, (TP.id IS NOT NULL) AS done
FROM myapp_place P
LEFT OUTER JOIN myapp_team_places TP
ON P.id = TP.place_id AND TP.team_id = %s

(You’ll also need to add an ORDER BY clause to return the Place objects in the order you want, but since I can’t see that part of your model, I can’t tell what that clause ought to look like.)

I don’t know how to express this query using Django’s object-relational mapping system, but you can always run it using a raw SQL query:

>>> sql = ''' ... as above ... '''
>>> places = Place.objects.raw(sql, [team.id])
>>> for p in places:
...     print p.id, bool(p.done)
...
1 True
2 True
3 False

1👍

A more optimal solution would be:

def done(self):    
    places = Place.objects.values_list('pk', flat=True)
    team_places = self.places.values_list('pk', flat=True)

    return [place in team_places for place in places]
👤caio

Leave a comment