Django - Use foreign key values directly


Django tip:

Use foreign key values directly.

Make sure to use the foreign key property instead of the foreign object ID.

  • DON'T: Song.objects.get(id=1).singer.id
  • DO: Song.objects.get(id=1).singer_id
from django.db import connection, reset_queries

from .models import Song

reset_queries()

# makes an extra SQL query to load the singer object:
Song.objects.get(id=1).singer.id
len(connection.queries) # => 2

reset_queries()

# an extra SQL query is not required:
Song.objects.get(id=1).singer_id
len(connection.queries) # => 1