python - Django操作資料庫遇到問題,無法查詢更新後的數據
PHP中文网
PHP中文网 2017-06-30 09:55:15
0
2
782

我更改了question_text的屬性並儲存


然後加入__str__()方法後再查詢所有Question,

我上面的程式碼是按照這個
http://www.yiibai.com/django/...來實現的,剛學,自己的步驟跟這個教程是一樣的,就是在添加__str__ () 方法後,教程的正確顯示如下圖:

#但是我自己進行測試,輸入指令,可是卻看不到我更改後的記錄,例如我將
q.question_text = "What's up?"
q.save()

儲存好修改後,執行下面的指令
Question.objects.all()
結果如下圖:
##請問這是什麼原因— —Django1.9,資料庫是預設的sqlite3

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(2)
typecho

感謝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:\Users\Administrator\AppData\Local\Programs\Python\Python35\myproject>python m
anage.py runserver

同時輸入


    C:\Users\Administrator\AppData\Local\Programs\Python\Python35\myproject>python m
anage.py shell
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AM
D64)] on win32
Type "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.注意縮排:

表述的可能不是很清楚,歡迎指正

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!