1 2 3 4 5
cards = Card.objects.all() for card in cards: photo_index = card.photo_address.rfind('/') card.thumb_url = card.photo_address[photo_index:].replace('/', '/th_')
Refactorings
No refactoring yet !
Tom Lynn
July 17, 2008, July 17, 2008 12:31, permalink
This is shorter, but arguably not clearer.
1 2 3 4
cards = Card.objects.all() for card in cards: card.thumb_url = '/th_'.join(card.photo_address.rsplit('/', 1))
gsson
August 20, 2008, August 20, 2008 13:49, permalink
Normally I would use something like
card.thumb_url = os.path.join(os.path.dirname(card.photo_address), "th_" + os.path.basename(card.photo_address))
It is not optimal, but it does convey the intent rather well. But since os.path.* performs OS-dependant operations (quite portable code provided you were actually realing with file-system paths rather than URLs). I think the following snippet would work properly on URLs though.
1 2 3 4 5 6
import os.path cards = Card.objects.all() for card in cards: card.thumb_url = urljoin(cards.photo_address, "th_" + os.path.basename(cards.photo_address))
gsson
August 20, 2008, August 20, 2008 13:50, permalink
Oops, missed an import when I copied; add "from urlparse import urljoin"
Code is self explanatory. Could this be written in a better way? Just curious