英文:
Django signal when model instance with custom field is deleted?
问题
我在我的Django应用中有一个自定义模型字段:
secret = VaultField(max_length=200)
它接受传递的值并将其保存到HashiCorp Vault中,并将其路径存储在数据库中,然后在访问时从Vault中检索它。
这一切都很好,我可以在许多模型上使用它。
但是现在,当我删除模型的实例时,它不会从Vault中删除。
我可以在所有具有VaultField
字段的模型上添加一个后删除信号,但那似乎是很多重复的工作。
在class VaultField(CharField):
类中是否有任何需要添加的内容?
或者,也许只有在删除字段时才触发后删除信号?
英文:
I've got a custom model field in my Django app:
secret = VaultField(max_length=200)
This takes the value passed and saves it to HashiCorp Vault and stores the path to it in the database, and retrieves it from Vault when accessing.
That's all good, I can use this on many models.
But now when I delete an instance of a model it doesn't delete it from Vault.
I could add a post delete signal on all models that have the VaultField
field, but that seems like a lot of duplicate work.
Is there anything to add in the class VaultField(CharField):
class?
Or maybe a post delete signal just on a field being deleted?
答案1
得分: 1
你可以重写具有VaultField的Models的delete()方法:
class YourModel(models.Model):
secret = VaultField(max_length=200)
def delete(self, *args, **kwargs):
# 放置您的自定义删除代码在这里
super().delete(*args, **kwargs)
你还可以在抽象模型中创建delete方法,然后在其他模型中继承它,以避免在所有模型中重复重写delete方法:
class Base(models.Model):
class Meta:
abstract = True
或者,您甚至可以将其编写在一个混合类中。
英文:
You can override the delete() method of Models which have the VaultField
class YourModel(models.Model):
secret = VaultField(max_length=200)
def delete(self, *args, **kwargs):
# Put your custom delete code here
super().delete(*args, **kwargs)
You can also make the delete method in a Abstract Model which can be inherited from in your other models, if you dont want to repeat the delete method override in all your Models.
class Base(models.Model):
class Meta:
abstract = True
Or you could even write it in a mixin class maybe
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论