Getting a random element in Django
- by Sarah
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?