Alexey
Alexey

Reputation: 449

How to avoid excess queries in django template?

I am newbie in Django and catch next issue: For example, I have next model:

class Player(model.Model):
    pass

class Game(models.Model):
    player1 = models.ForeignKey(Player, default=None, null=True, blank=True)
    player2 = models.ForeignKey(Player, default=None, null=True, blank=True)

    def is_only_one_player(self):
        if (self.player1 == None) ^ (self.player2 == None):
                return self.white or self.black
            else:
                return None

View will be very simple:

def return_scope(self):
    return render_to_response("temp.html", {"games": list(Game.objects.all())})

And this is part of my templete:

....
{% for game in games %}
   {% if game.is_one_player %}
      ... do something

As a result, when I see in "Django toolbar", for every "game" template makes query and as a summary for my case, I get about 200 queries! How I can avoid this behaviour?

Upvotes: 1

Views: 287

Answers (1)

schillingt
schillingt

Reputation: 13731

You can make use of select_related and prefetch_related

In your case it would be:

games = Game.objects.all().select_related('player1', 'player2')

Another option would be to change is_only_one_player to use the id's rather than the actual properties. This won't cause the ORM to hit the database.

if self.player1_id ^ self.player2_id:
    return self.white or self.black
return None

Upvotes: 1

Related Questions