Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Here's the code for my class (this is in the models.py file of my app):

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 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 >"?

2) Why don't I get any output when I call the object's id?

Thanks.

like image 928
MikeBrody Avatar asked Oct 24 '13 02:10

MikeBrody


1 Answers

Model.save is a method

You should run:

q.save()

Typing q.save in the console only prints the string representation of the method.

Because you never saved the model object to the database, the model object does not have a id.

like image 103
Leonardo.Z Avatar answered Sep 24 '22 10:09

Leonardo.Z