Question

I want to serve up entries for voting one at a time, starting with the latest unvoted, moving down to the oldest unvoted. If all entries have been voted on, I want to display a random voted entry.

In the Entry model I have a voted boolean;

models

class Entry(models.Model):
  text = models.CharField(max_length=15)
  score = models.IntegerField(default=0)
  pub_date = models.DateTimeField('date published')
  voted = models.BooleanField(default=False)
  def __unicode__(self):
    return self.text
  def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  was_published_recently.admin_order_field = 'pub_date'
  was_published_recently.boolean = True
  was_published_recently.short_description = 'Published recently?'

In entries:views I define the entries that get displayed in tables and for voting:

views

def index(request):
 context = {
  'latest_entry_list': Entry.objects.order_by('-pub_date')[:10],
  'high_entry_list': Entry.objects.order_by('-score')[:10],
  'low_entry_list': Entry.objects.order_by('score')[:10],
  'voting_entry_list': Entry.objects.filter(voted = False).order_by('-pub_date')[:1],
 }
 return render(request, 'entries/index.html', context);

'voting_entry_list': Entry.objects.filter(voted = False).order_by('-pub_date')[:1],

I call it a voting list, but it consists of just the sorted entry to show for voting.

This takes care of displaying the latest unvoted entries, and I know I need to check if voted is True, and in that case display a random entry, but i can't seem to get the syntax right to do this. I think a check on voted=False returns a null could let me do an else function to pick a random entry, but I can't seem to get it going in my code.

Could someone make a suggestion?

Was it helpful?

Solution

You can define a custom model manager for Entry model.

class EntryManager(models.Manager): def unvoted_or_random(self): unvoted_entries = self.filter(voted = False).order_by('-pub_date') if unvoted_entries: return unvoted_entries[:1] else: return self.all()[:1] #or any thing else you want

and then in your Entry model you can do something like.

class Entry(models.Model): ... objects = EntryManager()

and then you can get your required entries in the views by

Entry.objects.unvoted_or_random()

and pass it into the context..

I hope it would help..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top