Deleting user affects incremental unique reference which uses count of matching results. How to keep increment?

For a variety of reasons I might need to delete a user. A soft delete in which I simply delete all identifiable info and leaving some anonymised might not be an option. Additionally, if I delete the user inside the django admin site then it would be a hard delete.

The issue is that I have a model for the user which includes first_name, last_name, company_name, reference_id etc. The reference_id is created by using first 3 consonants of the last name, first 3 letters of the first name and then an incremental 3 digit number starting with 001. If any of the names have less than 3 letters the missing letters are replaced with an 'X'. The numeric part uses a model lookup with first 6 letters, counting the number of results. incrementing by 1 and using zfill to fill the missing number of digits. A full reference_id is like this: MDVTAS001 for example:

first_name_tres = first_name.lower()[0:3].ljust(3,'x')
print("first name 3: " + first_name_tres)
last_name_tres = last_name.lower().translate({ord(i): None for i in 'aeiou'})[0:3].ljust(3,'x')
print("last name 3: " + last_name_tres)
user_ref_count =  str(ProfileMember.objects.filter(reference_id__contains=(last_name_tres + first_name_tres)).count()+1).zfill(3)
print("user ref count: " + user_ref_count)
reference_id = last_name_tres + first_name_tres + user_ref_co

The issue with this method is that if for example is 2 users ie. MDVTAS001 and MDVTAS002 and I delete MDVTAS001 then the count is 1 and the next matching user will get MDVTAS002 but that already exists and since I am setting this value to be unique it will fail. Now if have 5 users and 2 are deleted the issue is compounded further.

How can I ensure that all the value is always incrementing higher even if users have been deleted?

last_record = ProfileMember.objects.filter(reference_id__startswith=(last_name_tres + first_name_tres)).order_by('reference_id').last()
if last_record:
    reference_id = last_name_tres + first_name_tres + str(int(last_record.reference_id[-3:]) + 1).zfill(3)
    reference_id = last_name_tres + first_name_tres + '001'
Back to Top