Desiigner
Desiigner

Reputation: 2316

Model's max_length field doesn't work on localhost

My model has a CharField called title with a max_length set to 30. I have a parser that parses data to the database and when I use it all on my localhost I don't have any errors.

After deploying, it happened there was an error:

django.db.utils.DataError: value too long for type character varying(30)

I found that it's trying to insert value that has 35 characters but this error doesn't appear on my localhost. I tried using shell and I managed to add a field that had 60 characters. What's wrong?

class Coin(models.Model):
    symbol = models.CharField(max_length=20)
    title = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.title} ({self.symbol})'

Upvotes: 1

Views: 387

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

I found that it's trying to insert value that has 35 characters but this error doesn't appear on my localhost. I tried using shell and I managed to add a field that had 60 characters. What's wrong?

Not all databases are that strict in enforcing constraints. Based on your comment, you use SQLite on your local host. In the documentation of SQLite, we read:

(...) Note that numeric arguments in parentheses that following the type name (ex: VARCHAR(255)) are ignored by SQLite - SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values. (...)

So that means that althought Django will add a length constraint, the database will not "enforce" it. For SQLite, VARCHAR(1), VARCHAR(255), NCHAR(55) all result in the same type of column: a TEXT.

On the "production server" side, you use a PostgreSQL database, and this database, as per documentation, enforces length constraints. In the documentation, we see the example:

INSERT INTO test2 VALUES ('too long');
ERROR:  value too long for type character varying(5)

Except for the length (here 5), the error matches completely. So PostgreSQL did enforce the length constraint, and did not accepted the data. The above is of course not "smoking gun evidence" that the error was generated by PostgreSQL, but it will require a lot of code analysis to confirm this in a rigorous way, so I hope this convinces you.

It is therefore advisable to at least test your application with the same "environment" for a (small) amount of time, since there are always small differences between databases, interpreters, etc. Yes most databases of course implement more or less the same system, but there are some small differences that can have some impact.

Upvotes: 1

Related Questions