Robert Johnstone
Robert Johnstone

Reputation: 5371

Django > form > is_unique()

I have the following on one of my forms:

def is_unique(self,item):
    ln = self.cleaned_data['letter_name']
    # checking for duplicate letter names
    if (Letter.objects.filter(item=item,letter_name=ln)):
        return False
    else:
        return True

Is there any way I could have a make_unique() function that would check the name like it's doing at the moment but if an example of the letter_name exists it tags an _n (_n = _01,_02,_03) on the end of letter_name.

Upvotes: 1

Views: 240

Answers (1)

boingboing
boingboing

Reputation: 171

This function should work if you call it from your is_unique function. When it is called we already know that there is at least one letter_name. Then we check how many letter_name with the tag beginning with the tagname and _ that has been created by filtering with startswith (I guess that this only works if _ isn't in the non altered letter_heads).

def make_unique(self, item, ln):
    ln_count = Letter.objects.filter(item=item, letter__startswith=ln+'_').count() + 1
    unique_ln = "{ln}_{count}".format(ln = ln, count = ln_count)
    return unique_ln

startswith is case-sensitive, if you want to use case-insensitive use istartswith.

Upvotes: 1

Related Questions