Optimise Two Sql Queries And A List Comprehension
I have those two models (simplified): class Place(OrderedModel): name = models.CharField(max_length=100) class Team(models.Model): name = models.CharField(max_length=100)
Solution 1:
You need this SQL query:
SELECT P.id, (TP.id ISNOTNULL) AS done
FROM myapp_place P
LEFTOUTERJOIN 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
Solution 2:
A more optimal solution would be:
defdone(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]
Post a Comment for "Optimise Two Sql Queries And A List Comprehension"