Identifying a new instance of a model in Django Save with UUID pk

If I have a model that has a primary key UUID, and the user can set the value at creation, is there a way to tell the method savethat the instance is new?

Previous methods for checking automatically assigned fields: In the custom save () method of the django model, how should you identify a new object? does not work.

+4
source share
2 answers

You can use django-model-utils TimeStampedModel (you can also use django-extensions TimeStampedModel or make your own).

This provides every model a createdand modified. Then compare the timedelta between the fields of the new instance createdand modifiedwith an arbitrary time difference (in this example, 5 seconds are used). This allows you to determine if the instance is new:

def save(self, *args, **kwargs):
    super(<ModelName>, self).save(*args, **kwargs)

    if (self.modified - self.created).seconds < 5:
        <the instance is new>   
0
source

saveaccepts an optional parameter force_insert. Passing this as True will force Django to do INSERT. See the documentation .

-1
source

All Articles