1

I want to make a simple ID counter for a model in django. I'd prefer it to start at 1000 instead of 0, so I'm thinking it might be better not to use the built in id function, as I've tried to do here:

    def __str__(self):

    return "Job #" + str(id) 

This (and all other attempts that involve writing a function) just return something like this:

  Job #<built-in function id>

Maybe it's easier to just use a for loop somehow?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
pilks7
  • 63
  • 6

1 Answers1

1

Python has a builtin function named id [Python-doc]. It calculates a number for a given object that remains fixed throughout the life of the object, and unique as well.

In case you thus use id in a function, and you do not declare a local variable (or a variable in a more local scope) named id. The lookup of the name id will result in this function.

But what you here want is the id of an object: the self object. So you need to use self.id instead:

def __str__(self):
    return "Job #" + str(self.id)

Or cleaner formatting:

def __str__(self):
    return "Job #{}".format(self.id)

Since it is not guaranteed that a model has an id column (since one can define another primary key), it is probably safer to use .pk instead:

def __str__(self):
    return "Job #{}".format(self.pk)

About starting the primary key, there are some questions (with answers) to that, like this and this. But the point is, that these are usually auto-increment fields, and the sequence that is used to assign id's is typically database dependent. As a result, there is no straightforward way to solve this problem, since some database systems at startup calculate the maximum of the assigned ids and then assign the next one each time. Although some solutions exist, those are typically not generic, and another database backend might work differently.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555