[Fixed]-Django: Which database call is faster/better?

1👍

request.user.user_profile makes an SQL query to get user profile, then user_profile.games_liked.all() makes second sql query to get liked games.

So, form this point of view Game.objects.filter(likes=request.user) is better.

You can check what sql was executed, in shell, by looking into connection.queries variable (available only if setting DEBUG=True)

from django.db import connection

user.user_profile.games_liked.all()
Game.objects.filter(likes=user)._as_sql(connection)

print(connection.queries)

Anyway, your example seems broken. ManyToMany field creates whole new table to store relationships. And you have linked games twice:

  • UserProfile -> _m2m_table -> Games (by UserProfile.games_liked)
  • User -> _m2m_table -> Games (by Games.likes)

You should remove one field.

Django creates shortcuts to get access to relation from opposite side. That is what related_name stands for. So for your Game model, use have access to users by game.likes, and from user you have access to games by user.likes, b/c you have declared related_name='likes'

Leave a comment