2015-09-02 82 views
0

我剛開始使用Django,我正在通過文檔here來構建我的第一個應用程序,但是我遇到了與SQLite的數據庫訪問API相關的某種問題。問題使用SQLite設置Django數據庫訪問API

我的目錄結構是這樣的:

我已編輯的文件只有models.pysettings.py,它是從文檔的所有代碼。

models.py:

from django.db import models 

class Question(models.Model): 
    # ... 
    def __str__(self):    # __unicode__ on Python 2 
     return self.question_text 

class Choice(models.Model): 
    # ... 
    def __str__(self):    # __unicode__ on Python 2 
     return self.choice_text 

import datetime 

from django.db import models 
from django.utils import timezone 


class Question(models.Model): 
    # ... 
    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 

只是我對settings.py所做的更改都將我的時區TIME_ZONE = 'US/Pacific'並添加'polls',INSTALLED_APPS。 (爲了充分披露,我已經設置了我的urls.py只是爲了測試hello world,這不是文檔的一部分,但我不認爲這是造成問題的原因,下面是如果相關的代碼)。

urls.py:

from django.conf.urls import patterns, include, url 
from django.contrib import admin 
from django.views.debug import default_urlconf 
from django.http import HttpResponse 

def hello(request): 
    return HttpResponse('Hello world!!!') 

urlpatterns = patterns('', 
    # Examples: 
    url(r'^$', hello), 
    # url(r'^blog/', include('blog.urls')), 

    #url(r'^admin/', include(admin.site.urls)), 
    #url(r'^$', default_urlconf), 
) 

現在,我正在進入的問題是,當我到了「用API播放」一節。當我在該部分中第二次打開python manage.py shell時,我應該能夠使用命令Question.objects.all()並得到結果[<Question: What's up?>]「What's up?」是question_text的值。問題是我仍然得到結果[<Question: Question object>]而不是question_text值。

我已經回去並重新創建我的應用三次,希望在安裝過程中錯過了某些內容,但每次都會遇到同樣的問題,我似乎完全按照文檔進行操作。我在這裏錯過了什麼嗎?

+1

您是否已將'__repr__'或'__unicode__'方法添加到Question類? – darkryder

+0

你的意思是使用'__unicode__'而不是'__str__'? – 123

+0

不知道這是否有幫助,但當我使用命令Question.objects.filter(question_text__startswith ='What')''我得到'FieldError:無法將關鍵字'question_text'解析到字段中。選擇是:id' – 123

回答

1

首先,確保models.py比賽用什麼在本教程

from django.db import models 

class Question(models.Model): 
    question_text = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published') 

    def __unicode__(self):    # __str__ on Python 3 
     return self.question_text 

    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 


class Choice(models.Model): 
    question = models.ForeignKey(Question) 
    choice_text = models.CharField(max_length=200, default="") 
    votes = models.IntegerField(default=0) 

    def __unicode__(self):    # __str__ on Python 3 
     return self.choice_text 

給出的含量,同時確保在遷移是最新的。

如果您正在運行python 2,請使用__unicode__,否則請使用__str__

這應該爲你解決問題。