Django makemigrations cannot detect change when changing custom field overriding charfield.

72 views
Skip to first unread message

김지환

unread,
Mar 13, 2017, 8:05:02 AM3/13/17
to Django users
# category.py

from django.db.models.fields import CharField


class CategoryField(CharField):
verbose_name = "category"
max_length = 40

NORMAL = 'normal'
PUBLIC = 'public'

choices = (
(NORMAL, "normal"),
(PUBLIC, "public),
)

def __init__(self, *args, **kwargs):
kwargs['max_length'] = self.max_length
kwargs['choices'] = self.choices
kwargs['verbose_name'] = self.verbose_name
kwargs['blank'] = True
kwargs['null'] = True
kwargs['default'] = self.NORMAL
super().__init__(*args, **kwargs)


# in my models.py
class Car(models.Model):
    category = CategoryField()



When I use custom field overriding django CharField, field changes that `max_length`, `choices` not detected by django makemigrations command.

Add field migration works fine, and verbose_name, blank, null changes are detected by makemigrations command.
However, when I change max_length and choices, django makemigrations cannot detect changes.

I checked return value of my CategoryField's deconstruct method, and the result is fine.
Also, if max_length is set like `CategoryField(max_length=50)`, makemigrations can detect changes.

Why django makemigrations cannot detect changes when set max_length and choices in __init__ method?







Tim Graham

unread,
Mar 13, 2017, 9:43:53 AM3/13/17
to Django users
It looks like you need to add a CategoryField.deconstruct() method.

https://docs.djangoproject.com/en/stable/howto/custom-model-fields/#custom-field-deconstruct-method

김지환

unread,
Mar 14, 2017, 2:09:12 AM3/14/17
to Django users
CategoryField subclassed CharField, so I think I don't need to add deconstruct method in CategoryField.

And, when call CategoryField().deconstruct(), the values return correctly.

Why django makemigrations cannot detect max_length and choices change?




2017년 3월 13일 월요일 오후 10시 43분 53초 UTC+9, Tim Graham 님의 말:

Tim Graham

unread,
Mar 14, 2017, 7:56:14 AM3/14/17
to Django users
CategoryField.__init__() has lines like kwargs['max_length'] = self.max_length

That's going to ignore any custom max_length that you provide in the model field's definition, hence those changes aren't detected in migrations.
Reply all
Reply to author
Forward
0 new messages