Opened 7 years ago

Closed 7 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: UI/UX:


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

    "id" integer NOT NULL PRIMARY KEY,
    "name" text NOT NULL
    `name` longtext NOT NULL

In the 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')

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

p = Person('name'=Bob)

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 Changed 7 years ago by Daniel Pope <dan@…>

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

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