问题描述
我个人喜欢使用:
从django.db导入模型
从django.db.models.signals导入pre_save
class MyModel(models。模型):
...
def custom_action_before_saving(发送者,实例,* args,** kwargs):
...
pre_save.connect(custom_action_before_saving,sender = MyModel)
但是我想知道是否有一段时间或更好的任务在模型类中:
从django.db导入模型
类MyModel(models .Model):
...
def save(自己):
...
super(MyModel,self).save()
我问这个问题是因为有一个覆盖的例子Django的文档页面中的 save()
方法(上面提供的链接),所以我认为这不是一个坏习惯。
让我们采用例如,文档说:
这是否意味着覆盖保存
您不会发现任何性能差异。
它们都不是黑客或错误的编码方法。
如果您在覆盖保存方法或从其他位置进行保存时获取循环导入,则可以使用信号。
我遵循一种模式,如果更改属于同一模型,则覆盖save方法,否则,如果它们属于未链接到当前模型的其他模型(一对一或一对多),使用信号。
Personally I like using signals:
from django.db import models
from django.db.models.signals import pre_save
class MyModel(models.Model):
...
def custom_action_before_saving(sender, instance, *args, **kwargs):
...
pre_save.connect(custom_action_before_saving, sender=MyModel)
But I wonder if there're some times or task when is better override the save method in a model class:
from django.db import models
class MyModel(models.Model):
...
def save(self):
...
super(MyModel, self).save()
I am asking this because there's an example of overriding the save()
method (link provided above) in Django's Documentation page, so I don't think it's a bad practice.
Let's take pre_save()
as example, docs says:
Does it means that overriding save
has the same effect over performance that using signals?
You wouldn't find any performance difference. Neither of them are hacks or "wrong" coding method. It's all how you like it.
You can use signals if you are getting circular imports when overriding save method or when saving from somewhere else.
I follow a pattern where, if the changes belong to same model, override the save method, else if they belong to a different model which isn't linked to the current model (by one to one or one to many), use signals.
这篇关于Django-什么时候应该使用信号,什么时候应该覆盖save方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!