开发者

Getting a random element in Django

开发者 https://www.devze.com 2022-12-22 21:38 出处:网络
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:

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 开发者_JAVA百科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?


OK, two things.

Firstly, the default string representation of a Django model instance is "Modelname object". To change this, define a __unicode__ method on the class - in your case, you just want it to return self.slogan.

Secondly, your slice is a queryset, because that's what you've asked for with [:1] - ie 'return a list consisting of all elements up to element 1'. If you just wanted a single element, you should use [0].


The slice is wrong. [:1] generates a list with one element (the first) in it, but you want probably the first element without the list.

slogan = Slogan.objects.order_by('?')[0].slogan
0

精彩评论

暂无评论...
验证码 换一张
取 消