Search code examples
djangosavegeneric-relations

Why can't I save my model with a generic relation twice in Django?


I got a model TrackedItem with a generic relation linking to any model it is supposed to track.

If I do that:

t = TrackedItem(content_object=MyModel)
t.save()
t.save()

I get :

IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")

Indeed, the first save has created an entry with "1" as a PK. But the second save should not insert, it should update.

How am I suppose to update a model I can't save twice?

With an ordinary model I can save as much as I want.

EDIT : it may be not related at all with generic relations.

I'm having a overrided save, and I call super in it, this way :

super(TrackedItem, self).save(self, *args, **kwargs)

if I do it this way, it works:

model.Model.save(self, *args, **kwargs)

Solution

  • Your problem is most likely because of wrong use of 'super'. It should be like this:

    super(TrackedItem, self).save(*args, **kwargs)