Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce char(N) datatype instead of varchar(N) in django model field

As per django docs https://docs.djangoproject.com/en/1.9/topics/db/models/

it's ORM create varchar field instead of char.

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

and equivalent sql statement

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

so here we can see it is using varchar, but can I use char instead. I'm unable to find a way. apart from manually altering the column

like image 432
rocktheparty Avatar asked Dec 24 '22 11:12

rocktheparty


2 Answers

For those who struggle with the anwser given by @andrai-avram, this is what that would look like:

from django.db import models
class ActualCharField(models.CharField):
    def db_type(self, connection):
        varchar: str = super().db_type(connection)
        char: str = varchar.replace('varchar', 'char')
        return char

And then just use this class instead of the default django.db.models.CharField

like image 128
Ken Avatar answered Jan 04 '23 14:01

Ken


I think your best bet is to write a custom field type, base it on CharField and alter its db_type() method. Check relevant example here

like image 20
Andrei Avram Avatar answered Jan 04 '23 14:01

Andrei Avram