Hi all,


down votefavorite 
<https://stackoverflow.com/questions/42011956/django-custom-model-fields#>

I am trying to create a Model Fields that is basically a AutoField, but in 
base 36.

Here my definition:

  class AutoBase36Field(models.AutoField):
        description = _("AutoField on base36")

        @staticmethod
        def base36encode(number):

        try:
            number = int(number)
        except:
            raise TypeError('number must be an integer')

        if not isinstance(number, int):
            raise TypeError('number must be an integer')
        if number < 0:
            raise ValueError('number must be positive')

        alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '']

        while number:
            number, i = divmod(number, 36)
            base36 = alphabet[i] + base36

        return base36 or alphabet[0]

    @staticmethod
    def base36decode(string):
        if string is None:
            return None
        return int(string, 36)

    def to_python(self, value):
        if value is None:
            return value
        try:
            return self.base36encode(value)
        except (TypeError, ValueError):
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        return self.base36encode(value)

    def get_prep_value(self, value):
        if value is None:
            return None
        return self.base36decode(value)

And here is a Model class I am using:

class Content(models.Model):

    mzk_id = AutoBase36Field(auto_created=True, primary_key=True, 
serialize=False, verbose_name='ID')
    name = models.TextField()

I have a test failing:

def test_incrementation_of_content_mzk_id(self):

    content1 = Content(name="a")
    content1.save()

    mzk_id_1 = int(content1.mzk_id, 36)

As mzk_id is kept as an integer. Basically when creating the incremented 
field, Django doesn't go through to_python()... I am not sure why...

Does anyone could help me up?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2c4300e7-80af-4fc5-b71c-31d6c0814a06%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to