Devin Naquin

Mar 6

Worst Line of Code and Why

I needed to grab the latest Link object for a certain Forum from Django’s ORM.

Normally, I’d do this with:

link = forum.link_set.order_by('-id')[0]

But for some reason, adding the slice (which adds a limit to the SQL query), was considerably slowing down the call. Whereas, just getting the iterator was fine.

link_qs = forum.link_set.order_by('-id')

Which is disturbing. I haven’t figured out why, but I wanted to get the code I was working on done before figuring out why this query was slow, so I hacked around it.

So, of course, I could just convert that QuerySet to a list and index the list with:

link = list(forum.link_set.order_by('-id'))[0]

But that would load the entire result into memory. My results could potentially be extremely large, so I didn’t want to go down that route.

So I wrote the obvious solution, using the iterator, but only saving the first result. Which turned out to be one of the worst lines of code I’ve ever written.

In all it’s glory:

for link in forum.link_set.order_by('-id'):
    break

Comments (View)
blog comments powered by Disqus
Page 1 of 1