简体   繁体   English

为什么我的数据库不能在此Python / Django应用程序中工作?

[英]Why isn't my database working in this Python/Django app?

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)为什么我看到“ <绑定方法Question.save of>”?

2) Why don't I get any output when I call the object's id? 2)为什么在调用对象的ID时没有得到任何输出?

Thanks. 谢谢。

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。

您必须运行q.save()命令,因为save()是一种方法,并且可以通过适当的表示形式进行访问。q.save仅通过该q变量中的字符串进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM