开发者

Can this be done with the ORM? - Django

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!


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜