gremmie@1: """ gremmie@1: pick_potd is a custom manage.py command for the POTD application. gremmie@1: It is intended to be called from a cron job at midnight to pick the gremmie@1: new POTD. gremmie@1: """ gremmie@1: gremmie@1: import random gremmie@1: from django.core.management.base import NoArgsCommand gremmie@1: gremmie@1: from potd.models import Current gremmie@1: from potd.models import Sequence gremmie@1: from potd.models import Photo gremmie@1: gremmie@1: def get_sequence(): gremmie@1: try: gremmie@1: s = Sequence.objects.get(pk=1) gremmie@1: if s.seq: gremmie@1: return [int(x) for x in s.seq.split(',')] gremmie@1: except: gremmie@1: pass gremmie@1: return [] gremmie@1: gremmie@1: def new_sequence(): gremmie@1: the_ids = Photo.objects.values_list('id', flat=True).order_by('id') gremmie@1: ids = [] gremmie@1: for id in the_ids.iterator(): gremmie@1: ids.append(int(id)) gremmie@1: gremmie@1: random.shuffle(ids) gremmie@1: try: gremmie@1: s = Sequence.objects.get(pk=1) gremmie@1: except Sequence.DoesNotExist: gremmie@1: s = Sequence() gremmie@1: gremmie@1: s.seq = ','.join([str(id) for id in ids]) gremmie@1: s.save() gremmie@1: return ids gremmie@1: gremmie@1: class Command(NoArgsCommand): gremmie@1: help = "Chooses the next POTD. Run this command at midnight to update the POTD." gremmie@1: #requires_model_validation = False gremmie@1: gremmie@1: def handle_noargs(self, **options): gremmie@1: try: gremmie@1: c = Current.objects.get(pk=1) gremmie@1: current = c.potd.pk gremmie@1: except Current.DoesNotExist: gremmie@1: c = Current() gremmie@1: current = None gremmie@1: gremmie@1: seq = get_sequence() gremmie@1: if current is None or len(seq) == 0 or current == seq[-1]: gremmie@1: # time to generate a new random sequence gremmie@1: seq = new_sequence() gremmie@1: # set current to the first one in the sequence gremmie@1: if len(seq) > 0: gremmie@1: try: gremmie@1: c.potd = Photo.objects.get(pk=seq[0]) gremmie@1: c.potd.potd_count += 1 gremmie@1: c.potd.save() gremmie@1: c.save() gremmie@1: except: gremmie@1: pass gremmie@1: else: gremmie@1: # find current in the sequence, pick the next one gremmie@1: try: gremmie@1: i = seq.index(current) gremmie@1: c.potd = Photo.objects.get(pk=seq[i + 1]) gremmie@1: c.potd.potd_count += 1 gremmie@1: c.potd.save() gremmie@1: c.save() gremmie@1: except: gremmie@1: pass gremmie@1: