Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CharField max_length 2^n vs 2^n-1

Why does one use max_length of CharField equal to 2^n whilst others use 2^n-1?

For example:

  • in django.contrib.gis.db.backends.postgis.models (django 1.3):

    class SpatialRefSys(models.Model, SpatialRefSysMixin):
        srtext = models.CharField(max_length=2048)
    
  • in django_openid_auth.models (djano-openid-auth 0.3):

    class Nonce(models.Model):
        server_url = models.CharField(max_length=2047)
    

Although it is not scientific measure, 2048 seems to be more popular than 2047, but 255 is more popular than 256. Django documentation says, that in MySQL max_length is restricted to 255 characters if you are using unique=True. But why would I use 2^n-1 instead od 2^n in other cases?

like image 545
jinowolski Avatar asked Aug 29 '11 16:08

jinowolski


People also ask

Why can't I set the Max character length of a Charfield?

This is probably because there is only a max character length contraint equivalent in SQL. Form Field CharField objects, on the other hand, do have a min_length parameter. So you'd have to write a custom ModelForm for this specific model and override the default admin model form with the custom one.

What is max_length in Charfield in Django?

One can store First Name, Last Name, Address Details, etc. CharField should be given an argument max_length for specifying the maximum length of string it is required to store. In production server, after the Django application is deployed, space is very limited. So it is always optimal to use max_length according to the requirement of the field.

What is Charfield in C++?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc.

What is the difference between Charfield and textfield?

CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput. CharField has one extra required argument:


1 Answers

You've mostly got it. It's not just the unique=True argument for 255, it's also that strings up to 255 long can sometimes be stored more efficiently.

So the answer is that there is maybe a point to doing it for 255 vs. 256, but for other lengths it's very likely to be pointless. Picking power-of-two lengths to begin with is often not done for a scientific reason (most of us haven't actually benchmarked that our 512-long field made our application run measurably faster than a 513-long field).

That said, there may be application-specific cases where the Django application is a frontend to a C application, where having N^2-1 strings is useful further down the line to efficiently store the additional terminating \0 byte.

like image 193
kdt Avatar answered Nov 09 '22 01:11

kdt