I have a Profile model where I have this unique field
referral_code = models.CharField(max_length=200, unique=True)
I have a generate_ref_code() that generate a code.
How can I make sure that this code is unique for the field?
new_ref_code = generate_ref_code()
Profile.objects.create(user=instance, referral_code=new_ref_code)
I can't do like
try:
new_ref_code = generate_ref_code()
Profile.objects.create(user=instance, referral_code=new_ref_code)
except IntegityError:
# generate a new code and try again
Because
IntegrityError exception only occur when try to save it
Profile.objects.create(user=instance, referral_code=new_ref_code).save()
Therefore how can I check this uniqueness of the code.