Why can't I save my shared relation model twice in Django?

I have a TrackedItem model with a generic relationship associated with whatever model it needs to track.

If I do this:

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

      

I get:

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

      

Indeed, the first save created an entry with "1" as a PC. But the second save shouldn't be inserted, it should be updated.

How do I go about updating a model that I cannot save twice?

With a regular model, I can save as much as I want.

EDIT: It may have nothing to do with generic relations at all.

I have an overridden save and I call super in it like this:

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

      

if i do this it works:

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

      

+2


a source to share


2 answers


Your problem is most likely due to misuse of "super". It should be like this:



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

      

+5


a source


I am guessing this is a DB transaction problem. Does DB-Commit notify two save calls? Perhaps your View is under a transaction. Com_mit_on_sucess controll.

2 Features:

  transaction.commit() # within transaction.commit_manually

      



or

  t.save(force_update=True) # 2nd save call

      

0


a source







All Articles