Can i change column type in database without updating Django model?

I have a django project which has created models for example:

from django.db import models

class Person(models.Model):
    title = models.CharField(max_length=30)
    description = models.CharField(max_length=30)

This creates table:

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "title" varchar(30) NOT NULL,
    "description" varchar(30) NOT NULL
);

Now i'm wondering can i change the column type to "LONGTEXT" without having to change the model? Would this cause an error? I don't have access to django code but i have access to database and i'm importing data, and values are more than 30 characters.

1 answer

  • answered 2020-05-22 13:30 Willem Van Onsem

    Would this cause an error?

    Likely not, since it will still communicating strings from and to the database.

    I don't have access to django code but i have access to database and i'm importing data, and values are more than 30 characters.

    Well depending on how the logic is implemented to create records, this can be a problem. A ModelForm for example, or a Serializer, will often perform validation, and thus check if the number of characters is indeed less than or equal to 30, if not it will not accept these values.

    That being said, it is often a (very) bad idea to let the models and the database run out of sync. Therefore it is probably better to change the field to a TextField, make migrations, migrate the database, and run the program:

    from django.db import models
    
    class Person(models.Model):
        title = models.CharField(max_length=30)
        description = models.TextField()

    I would advise not to alter the database and keep the Django data unchanged, since you eventually run into a situation where the database will accept other data than what the Django model anticipated on.