1👍
✅
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
0👍
If I understand correctly you want to use a CharField as a primary key and need to redefine the way django generates its value for new objects.
I think that you would complicate your life if you proceed in that way. Instead you can use base36 identifiers only in URLs and let your view translate them into the integer corresponding to the usual primary key, as in:
def my_view(request,base32_id):
pk = base32_to_int(base32_id)
obj = Model.objects.get(pk=pk)
...
- [Answer]-Validate nested form in Django
- [Answer]-Accessing list item in django template
- [Answer]-Access request from inherit class ( view )
- [Answer]-Django runtime error during insertion from admin
- [Answer]-Database Tables not defined in DJANGO models
Source:stackexchange.com