Getting a random element in Django

Posted by Sarah on Stack Overflow See other posts from Stack Overflow or by Sarah
Published on 2010-03-16T11:08:14Z Indexed on 2010/03/16 11:16 UTC
Read the original article Hit count: 188

Filed under:

I just finished the Django tutorial and started work on my own project, however, I seem to have missed something completely. I wanted to get a random slogan from this model:

from django.db import models

class Slogan(models.Model):
        slogan = models.CharField(max_length=200)

And return it in this view:

from django.http import HttpResponse
from swarm.sloganrotator.models import Slogan

def index(request):
        return HttpResponse(Slogan.objects.order_by('?')[:1])

However, the view just returns 'Slogan object'. Then I thought, maybe I can access the slogan string itself by simply appending .slogan to the slice, but that gives me an error indicating that the object I have is actually a QuerySet and has no attribute slogan.

I've obviously misunderstood something about Django here, but it just doesn't fall into place for me. Any help?

© Stack Overflow or respective owner

Related posts about django