I thought python's uuid.uuid4 guaranteed a unique value. Am I missing something?
Mark On Sun, Oct 22, 2017 at 3:58 PM, James Schneider <[email protected]> wrote: > > > On Oct 22, 2017 12:29 PM, "Andréas Kühne" <[email protected]> > wrote: > > Hi, > > I think you are correct with your pseudocode - you can do a > Model.objects.filter(unique_code==random_code).count() - and then loop on > that. It should work. > > > I wouldn't do this, it can lead to a race condition where you can possibly > end up with duplicate ID's if two objects are being inserted at the same > time. > > Ensure that you have a unique index on the ID column, then just create > your ID and try to insert it into the DB. Let the DB determine whether or > not it is unique, it is much better at this than any Python code you can > write. If it falils, catch the insertion error, change the ID, and try > again. > > Even if you did do this, you should use .exists() rather than .count(). > > Either way, your code should be prepared to deal with the potential for > duplicate ID's being inserted in to the database. > > -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 [email protected]. > To post to this group, send email to [email protected]. > 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%2BciWUK0AUMJ5xO9AO26fjMcdNvrJ- > 0Bwpi0Rpj4S2fcS4CA%40mail.gmail.com > <https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWUK0AUMJ5xO9AO26fjMcdNvrJ-0Bwpi0Rpj4S2fcS4CA%40mail.gmail.com?utm_medium=email&utm_source=footer> > . > > For more options, visit https://groups.google.com/d/optout. > -- 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 [email protected]. To post to this group, send email to [email protected]. 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/CAEqej2MZKeZQfmXig%2B1UHUpJaZtxhC%3DPiaEyij2rnFF1NRESZQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.

