gpt4 book ai didi

django - 如何删除Django中的默认值函数

转载 作者:行者123 更新时间:2023-12-04 18:29:32 25 4
gpt4 key购买 nike

在对 this question answer 的评论中我问如何删除具有默认值函数的字段。总结一下,示例代码是:

def get_deadline():
return datetime.today() + timedelta(days=20)

class Bill(models.Model):
name = models.CharField(max_length=50)
customer = models.ForeignKey(User, related_name='bills')
date = models.DateField(default=datetime.today)
deadline = models.DateField(default=get_deadline)

我对代码的问题是:

How do you remove the deadline field again while also deleting the get_deadline function? I have removed a field with a function for a default value, but now Django crashes on startup after removing the function. I could manually edit the migration, which would be ok in this case, but what if you simply changed the default function, and wanted to remove the old function?



我最终删除了引用它的迁移的默认部分,但是如何很好地删除它?

我能想到的唯一方法是压缩迁移,这样使用该函数的迁移就会消失,但这并不总是一种选择。

最佳答案

遵循 Historical Models 中的文档:

References to functions in field options such as upload_to and limit_choices_to and model manager declarations with managers having use_in_migrations = True are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations.

.....

To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files.


使用方法获取 default的值字段选项与 upload_to 中描述的相同 field 。如果您想删除该方法,文档本身为您提供了两个选项:
  • Squash 迁移 - 如果您不再需要这些
  • 编辑迁移文件:将函数复制到迁移文件并编辑迁移中的引用。

  • 评论更新:
    在编辑迁移文件的第 2 步中,我刚刚包含了文档中描述的方式。您可以选择如何准确地编辑迁移。您可以复制迁移文件中的函数并编辑引用,或者您可以从迁移文件中删除默认字段,或者您可以使用不同文件中的另一个函数。

    关于django - 如何删除Django中的默认值函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869781/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com