python - Django操作數(shù)據(jù)庫(kù)遇到問(wèn)題,無(wú)法查詢更新后的數(shù)據(jù)
問(wèn)題描述
我更改了question_text的屬性并保存
然后添加__str__()方法后再次查詢所有Question,
我上面的代碼是按照這個(gè)http://www.yiibai.com/django/...來(lái)實(shí)現(xiàn)的,剛學(xué),自己的步驟跟這個(gè)教程是一樣的,就是在添加 __str__() 方法后,教程的正確顯示如下圖:
但是我自己進(jìn)行測(cè)試,輸入命令,可是卻看不到我更改后的記錄,比如我將q.question_text = 'What’s up?'q.save()
保存好修改后,運(yùn)行下面的命令Question.objects.all()結(jié)果如下圖:請(qǐng)問(wèn)這是什么原因——Django1.9,數(shù)據(jù)庫(kù)是默認(rèn)的sqlite3
問(wèn)題解答
回答1:def __str__這應(yīng)該是模型Question的類方法,這個(gè)方法決定了你查詢時(shí)的返回,你定義的 return self.question_text,所以你查詢到對(duì)象的時(shí)候它會(huì)返回對(duì)象的question_text屬性, 但是你的書寫格式錯(cuò)誤,將這個(gè)方法定義到了類外面,它就變成了一個(gè)單一的函數(shù),跟這個(gè)類沒(méi)什么關(guān)系了, 你查詢的時(shí)候就會(huì)默認(rèn)返回一個(gè)Question對(duì)象。
回答2:感謝tianren124的解答,問(wèn)題得到了解決。首先需要修改models.py:models.py
# Create your models here.class Question(models.Model): def __str__(self):return self.question_text question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(’date published’) class Chioce(models.Model): def __str__(self):return self.choice_text question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) # 每個(gè)模型是django.db.models.Model類的子類 #def was_published_recently(self):#return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
更改好上面的model.py代碼后保存,打開(kāi)cmd,重新輸入
C:UsersAdministratorAppDataLocalProgramsPythonPython35myproject>python manage.py runserver
同時(shí)輸入
C:UsersAdministratorAppDataLocalProgramsPythonPython35myproject>python manage.py shellPython 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32Type 'help', 'copyright', 'credits' or 'license' for more information.(InteractiveConsole)>>> import django>>> django.setup()>>> from polls.models import Question, Chioce>>> Question.objects.all()[<Question: What’s up?>, <Question: What’s up?>, <Question: What’s up?>]>>>
可以看到,不同于之前問(wèn)題中的結(jié)果,當(dāng)輸入Question.objects.all()后,運(yùn)行結(jié)果是我更改q.question_tex后的值 “What’s up?解決:1.修改models.py
def __str__(self):return self.question_text
應(yīng)該放在
question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(’date published’)
def __str__(self):return self.choice_text
同樣要放在
question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
的前面,至于為什么我自己也不太明白。2.注意縮進(jìn):
表述的可能不是很清楚,歡迎指正
