Skip to content

Instantly share code, notes, and snippets.

@augustomen
Created March 28, 2023 20:21
Show Gist options
  • Save augustomen/fc4634c4a9369105f60d2ab571afb59c to your computer and use it in GitHub Desktop.
Save augustomen/fc4634c4a9369105f60d2ab571afb59c to your computer and use it in GitHub Desktop.
Django 4.1 - CharField that doesn't require max_length (for databases like PostgreSQL)
from django.db import models
class CharField(models.CharField):
"""A subclass of django.db.models.CharField that doesn't require max_length."""
def _check_max_length_attribute(self, **kwargs):
"""Allow max_length=None (the default value) without errors."""
if self.max_length is None:
return []
return super()._check_max_length_attribute(**kwargs)
def db_type(self, connection):
"""Removes (%(max_length)s) from generated db_type."""
result = super().db_type(connection)
if self.max_length is None:
result = result.split('(')[0]
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment