我有一个模型,我们保存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.enabled
从 False
更改为 True
时,或者反之亦然,我需要将 c.enabled
和 d.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 >> True
,a.enable >> False
,因为 a 尚未保存。
关于python - django - 当指定字段更改时如何自定义模型保存方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034780/