python - Django操作數據庫遇到問題,無法查詢更新后的數據
問題描述
我更改了question_text的屬性并保存
然后添加__str__()方法后再次查詢所有Question,
我上面的代碼是按照這個http://www.yiibai.com/django/...來實現的,剛學,自己的步驟跟這個教程是一樣的,就是在添加 __str__() 方法后,教程的正確顯示如下圖:
但是我自己進行測試,輸入命令,可是卻看不到我更改后的記錄,比如我將q.question_text = 'What’s up?'q.save()
保存好修改后,運行下面的命令Question.objects.all()結果如下圖:請問這是什么原因——Django1.9,數據庫是默認的sqlite3
問題解答
回答1:def __str__這應該是模型Question的類方法,這個方法決定了你查詢時的返回,你定義的 return self.question_text,所以你查詢到對象的時候它會返回對象的question_text屬性, 但是你的書寫格式錯誤,將這個方法定義到了類外面,它就變成了一個單一的函數,跟這個類沒什么關系了, 你查詢的時候就會默認返回一個Question對象。
回答2:感謝tianren124的解答,問題得到了解決。首先需要修改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) # 每個模型是django.db.models.Model類的子類 #def was_published_recently(self):#return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
更改好上面的model.py代碼后保存,打開cmd,重新輸入
C:UsersAdministratorAppDataLocalProgramsPythonPython35myproject>python manage.py runserver
同時輸入
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?>]>>>
可以看到,不同于之前問題中的結果,當輸入Question.objects.all()后,運行結果是我更改q.question_tex后的值 “What’s up?解決:1.修改models.py
def __str__(self):return self.question_text
應該放在
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.注意縮進:
表述的可能不是很清楚,歡迎指正
