On Oct 22, 2017 9:29 AM, "Andréas Kühne" <andreas.ku...@hypercode.se> wrote:

Hi,

When you say "globally unique" - I am supposing you mean within your
application?

What you need to do is set a field to be the primary key, see :
https://docs.djangoproject.com/en/1.11/topics/db/models/#
automatic-primary-key-fields


Not necessarily. The field only need be unique, but does not need to be the
primary key, and probably shouldn't be IMO. Data (in this case, an
arbitrary ID) should not be used for the internal linkage of the DB. That's
what PK's are for. What if the ID needs to be changed later? All of the
relations would also need to be updated, leading to a large headache at
best.


However - it would be simpler to use the standard primary key auto id
field, and then add another field to hold your unique ID in it. This could
then be created on the pre_save signal and you could write something that
randomly generates the unique ID field. See https://docs.
djangoproject.com/en/1.11/topics/signals/


Again, I have to disagree. This shouldn't be a pre_save signal. What
happens when a model save() fails due to a race condition where another
object grabs the ID that was generated in the pre_save signal? The save()
function is likely the best place, or maybe a post_save function that
generates the ID and updates the existing record with a unique ID value.
That way the model can save its data and be 'assigned' an ID as the next
operation. I would personally determine and assign everything in the model
save() function, though, and make it one operation with logic to handle
collisions.

-James

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWFMQsFhgtWeRgLHfObas2LrwmpOJ0aw25ePPuajzKgOw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to