Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid duplicate key names by adding suffix

I need to have my title as the keyname the problem is this could cause problems with duplicate keynames, how can i check if it exists and add -1 to the end if it does, or add -2 to the end if -1 exists.

keyName = "hello"
duplicates = Entry.get_by_key_name(keyName)
            if duplicates:
                keyName = keyName+("-1")

How do i loop through adding 1 until I find a unique name?

any help is much appreciated J

like image 894
user664546 Avatar asked Sep 07 '26 05:09

user664546


2 Answers

keyName = "hello"

testName = keyName
suffix = 0
while Entry.get_by_key_name(testName):
  suffix += 1
  testName = "%s-%d" % (keyName, suffix)

keyName = testName
like image 183
Drew Sears Avatar answered Sep 09 '26 23:09

Drew Sears


A different way to think about the problem:

from itertools import imap, dropwhile, count

def make_name(i):
    stem = "foo"
    return stem if i == 0 else "{0}-{1}".format(stem, i)

def in_universe(name):
    return bool(Entry.get_by_key_name(name))

seq = dropwhile(in_universe, imap(make_name, count()))
keyName = seq.next()
like image 21
FMc Avatar answered Sep 09 '26 22:09

FMc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!