简体   繁体   English

Django 迁移未检测到自定义字段更改

[英]Django custom field change not detected by migrations

I have multiple custom fields in Django. First, they extended PositiveSmallIntegerField as we used int choices like:我在 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)

Then I changed it to CharField and TextChoices :然后我将其更改为CharFieldTextChoices

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)

The problem is that I just realized that Django didn't detect the type change.问题是我刚刚意识到 Django 没有检测到类型更改。 When I change something like null=True to null=False it is detected, but the DB type is not changed from number to char.当我将null=True之类的内容更改为null=False时,它会被检测到,但数据库类型并未从数字更改为字符。

How can I make it work?我怎样才能让它发挥作用?

This very situation, and the solution for it, is 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,因为 Django 不会检测到更改并为其进行迁移...您必须创建一个新的自定义字段 class 并更新您的模型以引用它。

 class CustomCharField(models.CharField): ... class CustomTextField(models.TextField): ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM