【问题标题】:Deprecating fields in django modeldjango模型中的弃用字段
【发布时间】:2017-10-04 05:48:52
【问题描述】:

我正在规范化与 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

我的理解是,我需要在课堂上的某处添加类似于 warnings.warn('<field name> is deprecated', DeprecationWarning) 的内容,但我应该在哪里添加呢?

【问题讨论】:

标签: django python-3.x django-models deprecation-warning class-attributes


【解决方案1】:

你可以使用django_deprication.DeprecatedField

pip install django-deprecation

然后像这样使用

class Album(models.Model):
    name = DeprecatedField('title')

https://github.com/openbox/django-deprecation

【讨论】:

  • 你知道这是否适用于转换为外键?看起来应该,但好奇你是否尝试过。
【解决方案2】:

也许你可以使用 Django 的system check framework(在 Django 1.7 中引入)。

migrations docs 中提供了一些有趣的示例,使用系统检查框架来弃用 custom 字段。

看来您也可以使用这种方法在模型上标记 标准 字段。 应用于原始帖子中的示例,以下对我有用(在 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.
    )
    ...

有关更多详细信息,请参阅system check API reference,例如关于“唯一 ID”。

每当您调用runservermigrate 或其他命令(如in the docs 所述)时,都会显示以下警告:

System check identified some issues:

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

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

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

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

    • 不幸的是,我还不能冒险破坏任何现有功能
    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2013-02-03
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多