Good evening,
I know, I asked a similar Question just a while ago, but I still got problems in understanding the more detailled functions of a signal. So I'm hoping someone can help me out with this one!? As an example I have a class in my "models.py" like this one:
class ExampleModel(models.Model):
name = models.CharField(max_length=255, null=False, blank=False)
value1 = models.IntegerField()
value2 = models.IntegerField()
value_of_1_and_2 = models.IntegerField()
def __str__(self):
return self.name
I would like to have my field "value_of_1_and_2" filled automatically with the sum of the other two fields before saving... Is this possible? I tried some things and got stuck with a "pre_save" like this:
@receiver(pre_save, sender=ExameplModel)
def save(self, *args, **kwargs):
...
Thanks for all of your help and a nice evening to all of you!
Although the signals do logically similar things, they are slightly different from the save method in the model class. To be more specific, they answer the following questions in your head:
If we come to what you want; If I understood correctly, you want to leave value_of_1_and_2 field blank while saving your model, and you want django to save it in the background with a method you set.
First of all, I prefer to keep the signals and models apart for a clean look. So next to the models.py file, create the signals.py file.
signals.py :
from .models import ExampleModel
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=ExampleModel)
def pre_save_example_model(sender, instance, *args, **kwargs):
if not instance.value_of_1_and_2:
instance.value_of_1_and_2 = instance.value1 + instance.value2
Then make the following definition in apps.py for the signals to work (Let's consider the name of the application as Summing. You can replace it with your own.):
apps.py :
from django.apps import AppConfig
class SummingConfig(AppConfig):
name = 'summing'
def ready(self):
from . import signals
And the most important thing here is: since you will leave the value_of_1_and_2 field empty, you should update your field as follows. Otherwise Django will raise the error.
value_of_1_and_2 = models.IntegerField(blank=True, default=0)
That's all. Save the model by entering value1 and value2, then you will see the result.