迁移未检测到 Django 自定义字段更改
Django custom field change not detected by migrations
我在 Django 中有多个自定义字段。首先,他们扩展了 PositiveSmallIntegerField
,因为我们使用了 int 选择,例如:
class BusinessLegalFormField(models.PositiveSmallIntegerField):
choices = [(1,'SRO'), (2, ....]
def __init__(self, *args, **kwargs):
if not args or not args[0]:
kwargs.setdefault('verbose_name', 'Právna forma')
kwargs['choices'] = self.choices
super().__init__(*args, **kwargs)
然后我改成CharField
和TextChoices
:
class BusinessLegalFormField(models.CharField):
class Choices(models.TextChoices):
ZIVNOST = 'zivnost', 'Živnosť'
SRO = 'sro', 'Spoločnosť s ručením obmedzeným'
AS = 'as', 'Akciová spoločnosť'
def __init__(self, *args, **kwargs):
if not args or not args[0]:
kwargs.setdefault('verbose_name', 'Právna forma')
kwargs.setdefault('max_length', 64)
kwargs['choices'] = self.Choices.choices
super().__init__(*args, **kwargs)
问题是我刚刚意识到 Django 没有检测到类型更改。当我将 null=True
之类的内容更改为 null=False
时,它会被检测到,但数据库类型并未从数字更改为字符。
我怎样才能让它发挥作用?
这种情况及其解决方案是 described in the documentation:
You can’t change the base class of a custom field because Django won’t detect the change and make a migration for it... You must create a new custom field class and update your models to reference it.
class CustomCharField(models.CharField):
...
class CustomTextField(models.TextField):
...
我在 Django 中有多个自定义字段。首先,他们扩展了 PositiveSmallIntegerField
,因为我们使用了 int 选择,例如:
class BusinessLegalFormField(models.PositiveSmallIntegerField):
choices = [(1,'SRO'), (2, ....]
def __init__(self, *args, **kwargs):
if not args or not args[0]:
kwargs.setdefault('verbose_name', 'Právna forma')
kwargs['choices'] = self.choices
super().__init__(*args, **kwargs)
然后我改成CharField
和TextChoices
:
class BusinessLegalFormField(models.CharField):
class Choices(models.TextChoices):
ZIVNOST = 'zivnost', 'Živnosť'
SRO = 'sro', 'Spoločnosť s ručením obmedzeným'
AS = 'as', 'Akciová spoločnosť'
def __init__(self, *args, **kwargs):
if not args or not args[0]:
kwargs.setdefault('verbose_name', 'Právna forma')
kwargs.setdefault('max_length', 64)
kwargs['choices'] = self.Choices.choices
super().__init__(*args, **kwargs)
问题是我刚刚意识到 Django 没有检测到类型更改。当我将 null=True
之类的内容更改为 null=False
时,它会被检测到,但数据库类型并未从数字更改为字符。
我怎样才能让它发挥作用?
这种情况及其解决方案是 described in the documentation:
You can’t change the base class of a custom field because Django won’t detect the change and make a migration for it... You must create a new custom field class and update your models to reference it.
class CustomCharField(models.CharField): ... class CustomTextField(models.TextField): ...