python - Django:每次更新都会调用模型 __init__()

标签 python django

我的一个模型中有一个相当神秘的问题。我已经覆盖了 __init__ 如下:

class Program(models.Model)
    ...
    def __init__(self, *args, **kwargs):
        super(Program, self).__init__(*args, **kwargs)
        for m in Milestone.objects.all():
            try:
                ProgramMilestone.objects.create(milestone = m, program = self)
            except IntegrityError: # The link already exists.
                pass

其中 ProgramMilestone 是 MilestoneProgram 之间的链接器表(使用 through='...')。

我希望所有 Milestones 仅在程序创建时添加到 Program 中,但现在每当我在 Django 的管理界面中打开程序时,它都会运行for m... 循环(使得无法删除 Django 管理中的任何 ProgramMilestone 对象,因为它们只会在刷新时重新生成)。

我是否误解了 __init__ 的作用,如果是,我该如何创建这种行为(即仅在实例化时运行的一次性代码)?

最佳答案

如果我没听错,您想在创建程序时运行一些代码。

您可以使用 post_save 信号并检查 created 标志。

https://docs.djangoproject.com/en/dev/ref/signals/#post-save

通过让您的代码监听该信号,您可以在程序创建时运行您的代码,而不是更改。

关于python - Django:每次更新都会调用模型 __init__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6537239/

相关文章:

python - 高效,快速的numpy直方图

python - 如何在具有 60 个功能的 1000 万行数据库上加速 Django 查询聚合?

django - 使用 python_application Chef Recipe

python - 在/polls找不到页面

python - 在另一个列表python中搜索列表项的最佳方法?

python - Pandas:将数据框列转换为 dict,其中 col 标题作为 dict 键,col 值作为 dict 值

python - 如何在 Python 中处理长 SQL 语句字符串

javascript - Django Python : Can't access JS object passed via AJAX from Python QueryDict

python - Django 3.1 : StreamingHttpResponse with an async generator

Python:尝试导入循环