【问题标题】:Why isn't my database working in this Python/Django app?为什么我的数据库不能在这个 Python/Django 应用程序中工作?
【发布时间】:2013-11-02 13:29:27
【问题描述】:

我正在尝试完成 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) 为什么我看到“”?

2) 为什么我调用对象的id没有任何输出?

谢谢。

【问题讨论】:

    标签: python mysql django shell


    【解决方案1】:

    Model.save 是一个方法

    你应该运行:

    q.save()
    

    在控制台中键入 q.save 只会打印该方法的字符串表示形式。

    因为您从未将模型对象保存到数据库中,所以模型对象没有 id。

    【讨论】:

    • 谢谢!很高兴所有的打字都是值得的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多