[英]Why isn't my database working in this Python/Django app?
我正在嘗試完成Django教程,並且代碼中的所有內容都可以正常使用,直到嘗試保存並打印對象的實例變量為止。
這是我的課程的代碼(在我的應用程序的models.py文件中):
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
然后將其輸入到終端:
$ python manage.py sql polls
返回以下輸出:
BEGIN;
CREATE TABLE `polls_question` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`question_text` varchar(200) NOT NULL,
`pub_date` datetime NOT NULL
)
;
CREATE TABLE `polls_choice` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`question_id` integer NOT NULL,
`choice_text` varchar(200) NOT NULL,
`votes` integer NOT NULL
)
;
ALTER TABLE `polls_choice` ADD CONSTRAINT `question_id_refs_id_f3f98eca` FOREIGN KEY (`question_id`) REFERENCES `polls_question` (`id`);
COMMIT;
然后,將其輸入到我的終端中:
$ python manage.py syncdb
哪個返回:
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
然后在終端輸入此內容以啟動python shell:
$ python manage.py shell
這是終端內部的輸入/輸出:
In [1]: from polls.models import Question, Choice
In [2]: Question.objects.all()
Out[2]: []
In [3]: from django.utils import timezone
In [4]: q = Question(question_text="What's new?", pub_date=timezone.now())
In [5]: q.save
Out[5]: <bound method Question.save of <Question: Question object>>
#tutorial does not show this above line appearing
In [6]: q.id
#tutorial says I should get an output from this
我的問題:
1)為什么我看到“ <綁定方法Question.save of>”?
2)為什么在調用對象的ID時沒有得到任何輸出?
謝謝。
Model.save是一種方法
您應該運行:
q.save()
在控制台中鍵入q.save僅打印該方法的字符串表示形式。
因為您從未將模型對象保存到數據庫,所以模型對象沒有ID。
您必須運行q.save()命令,因為save()是一種方法,並且可以通過適當的表示形式進行訪問。q.save僅通過該q變量中的字符串進行訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.