I'm trying to complete the Django tutorial, and everything in my code is working until I try to save and print the instance variables of my object.
我正在尝试完成Django教程,我的代码中的所有内容都在工作,直到我尝试保存并打印对象的实例变量。
Here's the code for my class (this is in the models.py file of my app):
这是我的类的代码(这是在我的应用程序的models.py文件中):
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
Then I enter this into the terminal:
然后我把它输入终端:
$ python manage.py sql polls
Which returns this output:
返回此输出:
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;
Then I enter this into my terminal:
然后我把它输入我的终端:
$ python manage.py syncdb
Which returns this:
哪个返回:
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Then I enter this the terminal to start the python shell:
然后我输入这个终端来启动python shell:
$ python manage.py shell
And here's the input/output inside the terminal:
这是终端内的输入/输出:
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
My questions:
1) Why am I seeing "< bound method Question.save of >"?
1)为什么我看到“
2) Why don't I get any output when I call the object's id?
2)当我调用对象的id时,为什么我没有得到任何输出?
Thanks.
1 个解决方案
#1
7
Model.save is a method
Model.save是一种方法
You should run:
你应该运行:
q.save()
Typing q.save in the console only prints the string representation of the method.
在控制台中键入q.save只会打印方法的字符串表示形式。
Because you never saved the model object to the database, the model object does not have a id.
因为您从未将模型对象保存到数据库,所以模型对象没有id。
#1
7
Model.save is a method
Model.save是一种方法
You should run:
你应该运行:
q.save()
Typing q.save in the console only prints the string representation of the method.
在控制台中键入q.save只会打印方法的字符串表示形式。
Because you never saved the model object to the database, the model object does not have a id.
因为您从未将模型对象保存到数据库,所以模型对象没有id。