2

I am looking for a way to specify an IntegerField so that it has a certain maximum of digits. What I'm looking for is similar to max_length of a CharField. I have searched the internet and even in this forum, but they are all answers related to adding minimum and maximum values such as min_length and max_length or adding validators. So that they do not get confused, what interests me is to establish an IntegerField with a maximum of digits and not a maximum value. Is there a function that can provide me so that in the model a parameter can be added to this IntegerField?

E.g.: code = models.IntegerField('Code', primary_key=True, max_digits=8)

  • Write a validator. https://docs.djangoproject.com/en/1.11/ref/validators/ – Håken Lid Nov 07 '17 at 00:16
  • Look here someone did think about it yet. [https://stackoverflow.com/questions/849142/how-to-limit-the-maximum-value-of-a-numeric-field-in-a-django-model/849177](https://stackoverflow.com/questions/849142/how-to-limit-the-maximum-value-of-a-numeric-field-in-a-django-model/849177) – Coder949 Nov 07 '17 at 07:16

2 Answers2

0

That's what DecimalField is for.

code = models.DecimalField(max_digits=8, decimal_places=0, ...)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Since you're using base decimal, I'm assuming base 10, but you can use logarithmic properties to determine that. log() isn't the most accurate function, so you have to round to get the right number (fun trick I learned in high school, if you want to round, add 0.5, and truncate). So this would be a function that returns the number of digits that you could validate against, and if it's something other than base 10, you can just specify base=whatever

def digits(num, base=10):
    print(int(math.log(num, base) + 1.5))
bubthegreat
  • 301
  • 1
  • 9