Optimasi Database di Django Menggunakan Query select_related

Bandingkan 2 query ini:

Query 1:

data = Quote.objects.filter(published=True).order_by('-modified')

Query 2:

data = Quote.objects.select_related('author').filter(published=True).order_by('-modified')

Di template, kita panggil data author dengan:

{{ data.author.author_name }}

Jika menggunakan query 1, memanggil author berarti melakukan hit ke database lagi, karena di data belum ada author, beda dengan query 2, karena sudah kita panggil dengan select_related, panggilan ke author tidak akan hit database lagi.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s