If I have a model that has a UUID
primary key and the the user may set the value on creation, is there any way to tell within the save
method that the instance is new?
Previous techniques of checking the auto assigned fields: In a django model custom save() method, how should you identify a new object? do not work.
A UUID primary key will cause problems not only with generic relations, but with efficiency in general: every foreign key will be significantly more expensive—both to store, and to join on—than a machine word.
pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".
UUIDField is a special field to store universally unique identifiers. It uses Python's UUID class. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids.
To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
Use self._state.adding
. It defaults to True
and gets set to False
after saving the model instance or loading it from the DB.
You should also check the force_insert
argument of save
.
Note that this will not work if you attempt to copy an instance by changing its id
and saving (a common shortcut). If you need to detect this, you could override the instance saving and loading to also store the pk
on self._state
, then compare the current pk
with self._state.pk
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With