【问题标题】:Generating files after adding model instance through django admin interface通过 django 管理界面添加模型实例后生成文件
【发布时间】:2019-06-20 11:42:38
【问题描述】:

我正在为网站编写模型。当用户通过 Django admin 添加模型的实例时,我想捕获事件并自动生成文件,包括为那些创建的文件添加引用路径字段。

模型表单(用于管理站点)有一个可以被覆盖的clean 方法。我可以通过它创建和更新文件和字段。

def clean(self):
    info = self.cleaned_data.get('info')

    ... #Generate IO paths from info

    self.cleaned_data['template_path'] = template_path
    self.instance.template_path = template_path

    return self.cleaned_data

我需要区分addchange 事件,因此我不会编写文件并更改路径帖子对象的创建。有没有办法在clean 中做到这一点,或者我应该在其他地方寻找创建字段和更新字段?

【问题讨论】:

标签: django python-3.x django-models django-admin


【解决方案1】:

清理 ModelForm 并不一定意味着模型实例会被保存。

您可以在模型的 save() 方法或pre_save 信号中执行此操作,以便确定。

话虽如此,为了区分添加和更改,您可以在保存之前先在数据库中查询具有相同 id 的实例。

if instance.pk and instance.__class__.objects.filter(pk=instance.pk):
    # Editing existing instance, skip
    pass
else:
    # New instance. do whatever you want

在你的情况下 instance 变成 self.instance

【讨论】:

  • 您还可以使用 instance._state 保存该数据库查询。请参阅@Endre Both 在问题中的评论
  • 我是通过 save 方法实现的。更好的工作流程,但我只需要确保在我的条件检查和自定义字段更新之后调用 super().save()。效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2012-04-12
  • 2012-01-06
  • 1970-01-01
  • 2013-07-25
  • 2020-06-10
  • 2011-11-25
相关资源
最近更新 更多