Moving from Django signals to save override: How to translate the "created" parameter of a Django post_save signal for a save method override

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

Moving from Django signals to save override: How to translate the "created" parameter of a Django post_save signal for a save method override

问题

关于如何更改处理Django模型上的post_save事件的方法,您可以考虑以下方式。要替代接收器函数中的if created:语句,您可以重写MyModelsave方法,如下所示:

class MyModel(models.Model):
    # ... 

    def save(self, *args, **kwargs):
        if not self.pk:  # Check if the instance is being created
            self.do_something()
        super().save(*args, **kwargs)

这里,我们检查self.pk是否存在,如果不存在,则表示正在创建新实例,然后调用self.do_something()。然后,我们调用super().save(*args, **kwargs)来执行模型的默认保存操作。

对于pre_save信号,您可以采用类似的方法来检查是否正在创建实例。不过,pre_save信号在保存之前触发,所以您需要注意如何处理它,以避免不必要的操作。

如果您需要更多帮助或有其他建议,请随时告诉我。

英文:

I have made some bad decisions earlier regarding how I handle post_save events on a Django model and I am currently looking into changing my approach.

Let's begin by making my example. Here is my model.

class MyModel(models.Model):
    #... all my model creation and logic are here
    
    def do_something(self):
        # Actually do something, for the sake of simplifying the example, just write pass
        pass

Now, what I am using is a receiver function like this one. It works, but for many reasons that are mine, I want to stop using signal in this case.

@receiver(post_save, sender=MyModel)
def foo(sender, instance, created, **kwargs):
    if created:
        instance.do_something()

I imagine I could override the MyModel.save method, something like this:

class MyModel(models.Model):
    #... 

    def save(self):
        super().save()
        if created: # It is this line that I need to figure how to do. 
            self.do_something()

By what should I replace the if created: of my receiver function if I want to override the save() method? Or do you have something else to recommend?

I would also be curious if it is the same thing for pre_save signals.

答案1

得分: 1

如果我理解你的问题,你可以尝试检查当前模型实例的主键是否可用或不可用。

def save(self, *args, **kwargs):
    is_created = self.pk is None  # 检查实例是否正在创建
    
    super().save(*args, **kwargs)
    
    if is_created:
        self.do_something()
英文:

If i understand your question you can try checking if current model instance pk is available or not

def save(self, *args, **kwargs):
        is_created = self.pk is None  # Check if the instance is being created

        super().save(*args, **kwargs)

        if is_created:
            self.do_something()

huangapple
  • 本文由 发表于 2023年8月9日 09:54:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864107-2.html
匿名

发表评论

匿名网友

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

确定