Duplicate Django model instance without modifying python object

I am trying to create a method to duplicate a model instance

new_object = old_object.duplicate_in_db()

According to Django 3.2 documentation model instance can be duplicated in database by setting entity pk and/or id to None :

# Model method
def duplicate_in_db(self):
    self.pk = None
    self._state.adding = True
    # Some other duplication steps happens here e.g. duplicating OneToOneFields attributes
    # ...    

However a side effect is that original object has its id changed (along other attributes...)

old_object_pk = old_object.pk
new_object = old_object.duplicate_in_db()
print(old_object_pk == old_object.pk) # False

What would be an effective duplicate method/function without any side effect?

Refreshing from db with correct id do the job, Downside is having to do multiple database call.

    def duplicate_from_db(self):
        old_pk = self.pk  # storing for refreshing latter 
        self.pk = None
        self._state.adding = True
        self.prediction_result = None
        new_pk = self.pk
        self.pk = old_pk
        return MyModel.objects.get(pk=new_pk)
Back to Top