英文:
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事件时做出了一些错误的决定,现在我正在考虑改变我的方法。
让我们从创建一个示例开始。这是我的模型:
class MyModel(models.Model):
#... 所有的模型创建和逻辑都在这里
def do_something(self):
# 实际上做一些事情,为了简化示例,只写了pass
pass
现在,我正在使用一个像这样的接收器函数。它能工作,但出于我的一些原因,我想在这种情况下停止使用信号:
@receiver(post_save, sender=MyModel)
def foo(sender, instance, created, **kwargs):
if created:
instance.do_something()
我想我可以重写MyModel.save
方法,类似这样:
class MyModel(models.Model):
#...
def save(self):
super().save()
if created: # 这一行是我需要解决的地方
self.do_something()
如果我想重写save()
方法,我应该用什么来替换if created:
?或者你有其他建议吗?
我也很好奇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
如果我理解你的问题,你可以尝试检查当前模型实例的主键(pk)是否可用。
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论