I have the following model:
class SrdRevisionWording(ModelDiff):
srd_revision = models.ForeignKey(SrdRevision, on_delete=models.CASCADE)
word = models.CharField(max_length=50, null=False)
designation = models.CharField(max_length=200, null=False)
is_list = models.BooleanField(null=False, default=False)
parent_element = models.IntegerField(null=True) # ID of the Wording element in the previous SRD Revision
__original_instance = None
with_signal = True
def get_revision_history_message(self, created=False, deleted=False, updated_field=None, check_history=False):
if created:
return 'Word "{}" added'.format(self.word)
if deleted:
return 'Word "{}" deleted'.format(self.word)
match updated_field:
case 'word':
return 'Word {} changed to {}'.format(self.__original_instance.word, self.word)
case 'designation' | 'is_list':
return 'Word {} modified'.format(self.word)
The attribute __original_instance
is a custom model field (not in database).
This attribute is instantiated during the pre_save
signal :
@receiver(pre_save, sender=SrdRevisionDocument)
@receiver(pre_save, sender=SrdRevisionWording)
def model_pre_save_handler(sender, instance, **kwargs):
print('pre_save')
if instance.srd_revision.revision != 'A':
try:
previous_srd_revision_state = sender.objects.get(pk=instance.parent_element)
except sender.DoesNotExist:
instance.__original_instance = None
else:
instance.__original_instance = previous_srd_revision_state
print(instance.__original_instance)
The print(instance.__original_instance)
show me well the object SrdRevisionWording object (21)
.
I can also print the object in the post_save
signal :
@receiver(post_save, sender=SrdRevisionDocument)
@receiver(post_save, sender=SrdRevisionWording)
def handle_revision_history_element_changed(sender, instance, **kwargs):
print('signal')
print(instance.__original_instance)
if instance.with_signal is not False:
message = instance.get_revision_history_message(created=True, check_history=True)
The issue occurs on the last line when calling instance.get_revision_history_message()
.
I got the following error in the models.py file:
return 'Word {} changed to {}'.format(self.__original_instance.word, self.word)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'word'
I think it’s more on OOP misunderstanding from myself. But can someone explain me why the __original_instance seems not to be instantiate/accessible for the Model method here ?