Bartłomiej Bartnicki
Bartłomiej Bartnicki

Reputation: 1175

django query get last n records on database server

Hi accroding to django query get last n records

Is it good idea to get this last n record using [:n]? Can I do it on database serwer (for example in sql "select top 10"), not on server where is django?

Upvotes: 0

Views: 3248

Answers (2)

Surajano
Surajano

Reputation: 2688

I think for small records in the database say for 1k records, its fine using django query get last n records but for huge records in the table say 1M rows, its not the best way.

Getting n records from database server itself will be efficient than getting last n records as done here by django, because in this case total records are ordered then fetched and among those we are slicing last n records, if you have a choice to execute the query directly on a database server, you should go for it rather that using Django ORM as Django ORM is time and memory consuming.

order_by('?') queries may be expensive and slow, depending on the database backend you’re using. Details here

Upvotes: 1

NS0
NS0

Reputation: 6096

Yes, this is fine to use.

Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset.

Read the docs for more details.

Upvotes: 0

Related Questions