django模型中的弃用字段

django模型中的弃用字段,django,python-3.x,django-models,deprecation-warning,class-attributes,Django,Python 3.x,Django Models,Deprecation Warning,Class Attributes,我正在规范化与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)

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

我的理解是,我需要在类中的某个地方添加一些类似于
warning.warn('is deprecated',DeprecationWarning)
的内容,但是我应该在哪里添加它呢?

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

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

您可以使用
django\u去润滑。DeprecatedField

pip install django-deprecation
然后像这样使用

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

也许您可以使用Django(在Django 1.7中引入)

中提供了一些有趣的示例,使用system check框架对自定义字段进行弃用

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

有关更多详细信息,例如“唯一ID”,请参见

然后,无论何时调用
runserver
migrate
或其他命令,都会显示以下警告,如前所述:

(从文档中)也很高兴知道:

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


您可以将字段更改为属性,并在此处处理警告,如果可能,还可以返回相应的值。一个可能的解决方案:不幸的是,我不能冒险破坏任何现有功能。您是否知道,如果将其转换为外键,可能会发生这种情况?看起来应该是这样,但如果你试过的话,会很奇怪。
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 identified some issues:

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