python - django - 当指定字段更改时如何自定义模型保存方法

标签 python django save

我有一个模型,我们保存A,定义如下:

class A(models.Model):
   name = models.CharField('name', max_length=10)
   enabled = models.BooleanField('enabled', default=False)
   field1 = models.CharField('field1', max_length=10)
   field2 = models.CharField('field2', max_length=10)
   field3 = models.CharField('field3', max_length=10)
   parent = models.ForeignKey('self', null=True, blank=True) # hierarchy

以及该模型的一些对象实例,a、b、c、d。层次结构由父字段表示。

a 
|-- b
    |-- c
    |-- d

所以,我需要做的是,当 b.enabledFalse 更改为 True 时,或者反之亦然,我需要将 c.enabledd.enabled 更新为值:b.enabled

也就是说,当父级的 enabled 字段发生更改时,我需要将更改广播到子级实例。

出于性能考虑,我只需要在 enabled 字段真正发生更改时广播更改。并且不想在保存父实例时总是更新子实例,例如仅更新 field1 或 field2。

那么,有谁知道,实现这个逻辑的最佳方法是什么?提前致谢。

最佳答案

最好的方法是使用 django 信号 https://docs.djangoproject.com/es/1.10/ref/signals/

当您的模型调用方法save()时,您将调用方法change_status

from django.db.models.signals import pre_save

def change_status(sender, instance, **kwargs):
    # instance object is the model that you have called the method save
    a = A.objects.get(id=instance.id) # or B or C model
    if instance.enable:
        a.enable = False
        # my code.....

pre_save.connect(change_status, sender=A) 
# sender is the model that will be called every time you call the method save

就是这样 请记住,对象实例是更改之前的模型,因此 如果您有a.enable=True并在change_status信号中调用方法save(),您可以在不更改a.enable=True<的情况下进行查询 instance.enable >> Truea.enable >> False,因为 a 尚未保存。

关于python - django - 当指定字段更改时如何自定义模型保存方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034780/

相关文章:

python - 将网页内容从 bash/curl 下载到 python

python - Flask:将用户重定向到 html 页面的特定部分

django - Firefox WebFont 403 尽管有 S3 CORS 规则

c# - 如何在 WPF 中使用 OpenDialog 将文件复制到特定目录并设置文件名、扩展名?

ios - iOS文件创建可访问所有应用程序

Python异常语法差异?

python - 基于现有 DataFrame 和条件运算符创建新的 Pandas DataFrame

python - Django NameError [应用程序名称] 未定义

Django 值错误 : Can't do subqueries with queries on different DBs

ios - 将数据保存到 iOS 的最佳方式?