[Answer]-Django replicating a model object causing issue

1👍

Django looks at the primary key to determine uniqueness, so work with that directly:

too.pk = None
too.save()

Setting the primary key to None will cause Django to perform an INSERT, saving a new instance of the model, rather than an UPDATE to the existing instance.

Source: https://stackoverflow.com/a/4736172/1533388

UPDATE: err, using pk and id are interchangeable in this case, so you’ll get the same result. My first answer didn’t address your question.

The discrepancy here is between what is occurring in python vs. what can be reconstituted from the database.

Your code causes Django to save two unique objects to the database, but you’re only working with one python Too instance. When foo.save() occurs, the database entry for ‘foo’ is created with a reference to the DB entry for the first Too object. When coo.save() occurs, the database entry for ‘coo’ is created, pointing to the second, unique Too object that was stored via:

too.id = None #Copy the original 
too.save()

However, in python, both coo and foo refer to the same object, named ‘too’, via their respective ‘.too’ attributes. In python, there is only one ‘Too’ instance. So when you update too.id, you’re updating one object, referred to by both coo and foo.

Only when the models are reconstituted from the database (as the admin view does in order to display them) are unique instances created for each foreign key; this is why the admin view shows two unique saved instances.

👤bunn

Leave a comment