Q:

Custom model field change base of id

I am trying to get a base 36 string to use in my URLs.  I have written a function that converts a number to base 36, using letters to represent digits higher than 9.
I am trying to find a good way to set the default value of a character field equal to this function, but I am not sure how to get the Django default primary key value into it.  Any ideas?
I would think I could just put something like this into my model, but it does not work:
base_36 = models.TextField(default=convert_base(id, 36))

A:

You could either:

Override your model's save() method:
class YourModel(models.Model):

    base_36 = models.TextField()

    def save(self, *args, **kwargs):
        # will assign a value to pk
        super(YourModel, self).save(*args, **kwargs)
        # convert the pk to base 36 and save it in our field
        self.base_36 = convert_base(self.pk, 36)
        self.save()

Turn your base_36 field into a property:
class YourModel(models.Model):

    @property
    def base_36(self):
        return convert_base(self.pk,36)

# can call a property just like a field:
# print YourModel.objects.get(pk=1).base_36

