Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying new Model Instance in Django Save with UUID pk

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.

like image 931
Alex Rothberg Avatar asked Mar 18 '15 16:03

Alex Rothberg


People also ask

Is UUID good for primary key Django?

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.

What is PK in Django model?

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".

What is the use of UUID in Django?

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.

How do I create a Django instance model?

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() .


1 Answers

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.

like image 157
Jonathan Richards Avatar answered Oct 02 '22 09:10

Jonathan Richards