Django:从数据库中选择一个随机字符串

时间:2015-07-16 20:00:28

标签: django django-models django-views

我正在关注API docs并尝试从我的数据库中选择一个随机网址。但是,当我在views.py中运行以下代码时,我得到:

  

随机网址=网址对象

这应该是随机网址之一,例如我的MySQL数据库中/surveyseven/。谁能告诉我我做错了什么?

views.py

def begin(request):

    surveyurls = URLs.objects.all()    
    random_survey_index = random.choice(surveyurls)
    print 'Random URL = ', random_survey_index

models.py

class URLs(models.Model):
    SURVEYONE = models.CharField(max_length=25)
    SURVEYTWO = models.CharField(max_length=25)
    SURVEYTHREE = models.CharField(max_length=25)
    SURVEYFOUR = models.CharField(max_length=25)
    SURVEYFIVE = models.CharField(max_length=25)
    SURVEYSIX = models.CharField(max_length=25)
    SURVEYSEVEN = models.CharField(max_length=25)
    SURVEYEIGHT = models.CharField(max_length=25)
    SURVEYNINE = models.CharField(max_length=25)

夹具/ URLs.json

我使用灯具python manage.py loaddata URLs加载初始数据,我可以在我的数据库中看到它。

[
  {
    "model": "survey.URLs",
    "pk": 1,
    "fields": {
      "SURVEYONE": "/surveyone/",
      "SURVEYTWO": "/surveytwo/",
      "SURVEYTHREE": "/surveythree/",
      "SURVEYFOUR": "/surveyfour/",
      "SURVEYFIVE": "/surveyfive/",
      "SURVEYSIX": "/surveysix/",
      "SURVEYSEVEN": "/surveyseven/",
      "SURVEYEIGHT": "/surveyeight/",
      "SURVEYNINE": "/surveynine/"
    }
  }

]

1 个答案:

答案 0 :(得分:0)

class URL(models.Model):
    location = models.CharField(max_length=25)


[
    {
        "model": "survey.URL",
        "pk": 1,
        "fields": {
             "location": "/surveyone/"
        }
    },
    {
        "model": "survey.URL",
        "pk": 2,
        "fields": {
             "location": "/surveytwo/"
        }
    },
    {
        "model": "survey.URL",
        "pk": 3,
        "fields": {
             "location": "/surveythree/"
        }
    },

     ...
]


def begin(request):
    random_survey_obj = URL.objects.order_by('?').first()
    print('Random URL = {0}'.format(random_survey_obj.location))

关于order_by('?')阅读here