Django信号当具有自定义字段的模型实例被删除时?

huangapple go评论86阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月13日 00:33:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定