skeryl
skeryl

Reputation: 5295

Django inserts new object after save() method instead of update

When trying to update an existing Django model object (with the save() method), a new row is inserted instead.


For example:

>>> import datetime
>>> from data_lib.models import Meal
>>> m = Meal(name="My First Meal!", description="this is my first meal's description")
>>> print m.mealid
None
>>> m.save()
>>> print m.mealid
None
>>> m.save()

after that second save() method call, a duplicate entry was inserted into my table.


here is a sample of the model definition:

class Meal(models.Model):
    mealid = models.IntegerField(db_column='MealId', primary_key=True)
    name = models.CharField(db_column='Name', max_length=45, blank=True)
    description = models.CharField(db_column='Description', max_length=200, blank=True)

Upvotes: 2

Views: 1655

Answers (1)

skeryl
skeryl

Reputation: 5295

From the Django docs (1, 2):

The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.


The issue was in the model object's class definition.

Once I set the primary_key field to an AutoField, the issue went away.

My new model definition is as follows:


class Meal(models.Model):
        mealid = models.AutoField(db_column='MealId', primary_key=True)
        name = models.CharField(db_column='Name', max_length=45, blank=True)
        description = models.CharField(db_column='Description', max_length=200, blank=True)

An almost perfect auto-generation by Django!

Upvotes: 3

Related Questions