Opened 16 years ago

Closed 16 years ago

#8799 closed (invalid)

.save() and .objects.create() does not set the primary key when the model has an explicit primary key field

Reported by: vmihaylov@… Owned by: nobody
Component: Database layer (models, ORM) Version:
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Here is what I observed on django1.0-beta2 and 0.96 releases with MySQL or Sqlite3.
I have the following table:
Sqlite:

CREATE TABLE "Person" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" text NOT NULL
)
MySQL:
CREATE TABLE `Person` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `name` longtext NOT NULL
)

In the models.py I have

class Person(models.Model):
   id = models.IntegerField(primary_key=True)
   name = models.TextField()
   class Meta:
        db_table = u'Person'

When I issue:

p = Person.objects.create(name='Bob')
p.id

I get nothing. The record however is persisted.
Same happens with

p = Person('name'=Bob)
p.save()
p.id

If however the model is missing the id field and django auto generates it:

class Person(models.Model):
   name = models.TextField()
   class Meta:
        db_table = u'Person'

Than everything is OK. The id is set correctly.

Change History (1)

comment:1 by Daniel Pope <dan@…>, 16 years ago

Resolution: invalid
Status: newclosed

If you don't use AutoField, Django doesn't know that it needs to update the field after saving.

It assumes that you will always provide a value for the primary key, and if you don't, that you'll receive an OperationError from the DB-API. Because you've specified AUTO_INCREMENT in the database (or SQLite does that anyway), you aren't getting that error - the database is filling in a value behind Django's back.

Effectively this is just a mismatch between your database schema and your model definition.

Note: See TracTickets for help on using tickets.
Back to Top