views:

64

answers:

1

Hi folks,

I have a few item listed in a database, ordered through Reddit's algorithm.

This is it:

def reddit_ranking(post):
    t = time.mktime(post.created_on.timetuple()) - 1134000000
    x = post.score

    if x>0: y=1
    elif x==0: y=-0
    else: y=-1

    if x<0: z=1
    else: z=x

    return (log(z) + y * t/45000)

I'm wondering if there is any clever way of using Django's ORM, in order to UPDATE the models in bulk.

Without doing this:

items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7))
for item in items:
    item.reddit_rank = reddit_rank(item)
    item.save()

I know about the F() object, but I can't figure out if this function can be performed inside the ORM.


Any ideas?

Help would be very much appreciated!

+2  A: 

It's not much work to do it manually:

from django.db import connection

items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7))
cursor = connection.cursor()
cursor.executemany("UPDATE myapp_item SET reddit_rank = %s WHERE id = %s",
                   [(reddit_rank(item), item.pk) for item in items])
cursor.close()
insin
@insin not very familiar with cursor. Thank you very much, I'll try it out right now.
RadiantHex
How is this any more efficient than doing it through the ORM? The OP really wanted to do the whole thing via a single update query, but your way still calls `reddit_rank` once for every item.
Daniel Roseman