弃用 django 模型中的字段

cck*_*cck 8 django django-models class-attributes python-3.x deprecation-warning

我正在标准化与 Django 项目关联的数据库,并将字段移动到不同的表。作为实现过程的一部分,如果我的同事在添加新表后在我实际删除列之前尝试使用旧属性,我想向他们发出弃用警告。

class Asset(Model):
    model = models.CharField(max_length=64, blank=True, null=True)
    part_number = models.CharField(max_length=32, blank=True, null=True) # this will be a redundant column to be deprecated
    company = models.ForeignKey('Company', models.CASCADE, blank=True, null=True) # this will be a redundant column to be deprecated
    # other database fields as attributes and class methods
Run Code Online (Sandbox Code Playgroud)

warnings.warn('<field name> is deprecated', DeprecationWarning)我的理解是,我需要在课堂上的某个地方添加一些内容,但是我会在哪里添加它呢?

djv*_*jvg 8

也许您可以使用 Django 的系统检查框架(在 Django 1.7 中引入)。

迁移文档中提供了一些有趣的示例,使用 system-check-framework 来弃用自定义字段。

看来您也可以使用这种方法来标记模型上的标准字段。应用于原始帖子中的示例,以下内容对我有用(在 Django 3.1.6 中测试)。

class Asset(Model):
    ...
    company = models.ForeignKey('Company', models.CASCADE, blank=True, null=True)  
    company.system_check_deprecated_details = dict(
        msg='The Asset.company field has been deprecated.',
        hint='Use OtherModel.other_field instead.',
        id='fields.W900',  # pick a unique ID for your field.
    )
    ...
Run Code Online (Sandbox Code Playgroud)

请参阅系统检查 API 参考以获取更多详细信息,例如有关“唯一 ID”的信息。

runserver每当您调用、migrate或其他命令时,都会显示以下警告,如文档中所述:

System check identified some issues:

WARNINGS:
myapp.Asset.company: (fields.W900) The Asset.company field has been deprecated.
    HINT: Use OtherModel.other_field instead.
Run Code Online (Sandbox Code Playgroud)

也很高兴知道(来自文档):

...出于性能原因,检查不会作为部署中使用的 WSGI 堆栈的一部分运行。...


Jen*_*rup 0

我做了类似的事情 - 将字段转换为属性并处理那里的警告。请注意,这仍然会破坏您在字段上进行过滤的任何查询 - 只是有助于从实例访问属性。

class NewAsset(Model):
    model = models.CharField(max_length=64, blank=True, null=True)

class Asset(Model):
    @property
    def model(self):
        log.warning('Stop using this')
        return NewAsset.model
Run Code Online (Sandbox Code Playgroud)