As I am working through https://docs.djangoproject.com/en/1.4/topics/db/models/ , in django, I have started a new app called myapp and edited the the models.py file as the walkthrough defines:
class Person(models.Model):
GENDER_CHOICES = (
(u'M', u'Male'),
(u'F', u'Female')
)
name = models.CharField(max_length=60)
gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
Then I ran manage.py syncdb and tried to run the next few lines in the manage.py shell interactive prompt
>>> p = Person(name="Fred Flintstone", gender="M")
>>> p.save()
Traceback (most recent call last):
.…[I removed a few lines]...
DatabaseError: table myapp_person has no column named name
>>> p.gender
u'M'
>>> p.get_gender_display()
u'Male'
…so then I checked to see if sqlite3 had an object in the database called Person with the name column
C:\Users\djangoSite>python manage.py sql myapp
BEGIN;
CREATE TABLE "myapp_person" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(60) NOT NULL,
"gender" varchar(2) NOT NULL
);
And of course it does! So the Person model exists, however it doesn’t get the fields that I designed it with in models.py? I did a dir(Person) calls and it confirms that the name and gender fields aren’t in there… secondly, I did dir(p) and it does have them. I suppose that is because we just added them in with that tuple, so that’s not a surprise.
The big questions then are:
- Why can’t I ‘p.save()’?
- Why doesn’t the import call bring in objects with the fields that I designed in
models.py? - Is this by design?
- Am I just doing it wrong?
There is no column named name in your person table.
manage.py sql myappjust shows the sql that django generates based on your model. Not the actual table in sqlite. (of course it should match up) It is important that you enter your sqlite database and verfiy the table and its schema. I find that when developing I syncdb and make a change to the model later. Re-syncing db doesn’t modify the table. You have to delete the table then resync, or alter table.Please modify your question to reflect this issue, it doens’t look like you have any issues accessing or instantiating a person object.
No i don’t think this is by design, I believe these are common issues that arise as a new user is learning a new framework. I ran into all sorts of problems like these for weeks and months as I was learning, they will get farther and farther apart. Just make sure you are verifying things work correctly. Checking manage.py sql myapp isn’t that relevant. Checking your database to view the schem is more relevant. Django is a mature platform and when it gives you an error like
missing colum99.9% of the time it means exactly that it is transparent.