4

我正在规范化与 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)在课堂上的某个地方添加一些东西,但是我应该在哪里添加呢?

4

3 回答 3

2

您可以使用django_deprication.DeprecatedField

pip install django-deprecation

然后像这样使用

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

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

于 2018-09-09T14:37:25.820 回答
1

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

迁移文档中提供了一些有趣的示例,使用系统检查框架来弃用自定义字段。

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

有关更多详细信息,请参阅系统检查 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.

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

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

于 2021-02-18T14:43:06.423 回答
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
于 2017-05-05T22:16:24.770 回答