Reputation: 45
I'm trying to check if the unique id generated is unique in the database because it's only 6 characters.
class Images(models.Model):
uid = models.CharField(max_length=10, default=genid(), editable=False)
def genid():
uid = uuid.uuid4().hex[:6]
if Images.objects.get(uid=uid).exists():
uid = uuid.uuid4().hex[:6]
return uid
but it's not working. it tells me genid is not defined, Images is not defined. how can I fix this?
thanks
Upvotes: 0
Views: 175
Reputation: 477686
At that time, genid
is indeed not yet defined. Furthermore you should not call the function, since then it will take as default the result of the function. You should define this as:
class Images(models.Model):
def genid():
uid = uuid.uuid4().hex[:6]
if Images.objects.filter(uid=uid).exists():
uid = uuid.uuid4().hex[:6]
return uid
uid = models.CharField(max_length=10, default=genid, editable=False)
But normally these are defined outside the function, for example:
def genid():
uid = uuid.uuid4().hex[:6]
while Images.objects.filter(uid=uid).exists():
uid = uuid.uuid4().hex[:6]
return uid
class Images(models.Model):
uid = models.CharField(max_length=10, default=genid, editable=False)
You probably should replace the if
with a while
loop, since right now it is still possible that the second attempt fails as well.
Upvotes: 2