I tried this answer https://stackoverflow.com/a/28369908/9902571 in my model and done the following :-
from functools import wraps
def prevent_recursion(func):
#wraps(func)
def no_recursion(sender, instance=None, **kwargs):
if not instance:
return
if hasattr(instance, '_dirty'):
return
func(sender, instance=instance, **kwargs)
try:
instance._dirty = True
instance.save()
finally:
del instance._dirty
return no_recursion
My model:
class Journal(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname')
date = models.DateField(default=datetime.date.today)
voucher_id = models.PositiveIntegerField(blank=True,null=True)
by = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers')
to = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers')
debit = models.DecimalField(max_digits=10,decimal_places=2,null=True)
credit = models.DecimalField(max_digits=10,decimal_places=2,null=True)
My signal:
#receiver(post_save, sender=journal)
#prevent_recursion
def pl_journal(sender, instance, created, **kwargs):
if created:
if instance.by.group1_Name.group_Name == 'Indirect Expense':
Journal.objects.update_or_create(user=instance.user,company=instance.company,date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,to=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first(),debit=instance.debit,credit=instance.credit)
But the RecursionError of maximum recursion depth exceeded while calling a Python object stills comes while creating a journal object.
I want to pass the post_save signal for the same model (Journal) which when matches the condition in the signal gets called recursively.
Any anyone tell me what is wrong in my code?
Thank you
It is a little late but it may help others too. Instead of this, you can add dispatch_uid="identifier" to signal and it will work fine.
post_save.connect(function_name, sender=Model, dispatch_uid="identifier")
or
#receiver(post_save, sender=Model, dispatch_uid="identifier")
doc: https://docs.djangoproject.com/en/4.1/topics/signals/#preventing-duplicate-signals
Related
Django 1.11.1
Below are signal handlers. This is about saving history.
That is difference is signal (post_save and post-delete) and operation(+ or -).
The code is mostly duplicated. Could you help me understand how can I adhere to DRY principle here?
#receiver(post_save, sender=FramePlace)
def save_add_place(sender, **kwargs):
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(author=author,
operation="+",
frame=frame,
place=place)
#receiver(post_delete, sender=FramePlace)
def save_delete_place(sender, **kwargs):
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(author=author,
operation="-",
frame=frame,
place=place)
Just put you code in a function, it keeps the code simple (KISS) and you don't repeat yourself
#receiver(post_save, sender=FramePlace)
def save_add_place(sender, **kwargs):
create_frame("+", kwargs)
#receiver(post_delete, sender=FramePlace)
def save_delete_place(sender, **kwargs):
create_frame("-", kwargs)
def create_frame(operation, kwargs)
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(
author=author,
operation=operation,
frame=frame,
place=place
)
Can anyone see any issues with the code below? It's my save function for a model it gives them a GUID on first save. My my problem is when I save a new recipient (in the admin) it overwrites the last one added. Updates seem to work perfectly tho.
part of Models.py
class GUID():
make = hashlib.sha1(str(random.random())).hexdigest()
def save(self, *args, **kwargs):
if not self.recipientid:
self.recipientid = GUID.make
super(Recipient, self).save(*args, **kwargs)
GUID.make will be set at the time the GUID class is created, it won't re-calculated each time it's run. I don't know the rest of the context of how you're using GUID, but I'd have it be a function:
class GUID(object):
#staticmethod
def make():
return hashlib.sha1(str(random.random())).hexdigest()
...
def save(self, *args, **kwargs):
if not self.recipientid:
self.recipientid = GUID.make()
super(Recipient, self).save(*args, **kwargs)
Generally speaking, the way to do what you're trying to do is with a default lambda (in this example using a standard python uuid):
from django.db import models
from uuid import uuid4
class YourModel(models.Model):
# ...
recipientid = models.CharField(max_length=32, default=lambda: uuid4().hex)
I have a situation where when one of my models is saved MyModel I want to check a field, and trigger the same change in any other Model with the same some_key.
The code works fine, but its recursively calling the signals. As a result I am wasting CPU/DB/API calls. I basically want to bypass the signals during the .save(). Any suggestions?
class MyModel(models.Model):
#bah
some_field = #
some_key = #
#in package code __init__.py
#receiver(models_.post_save_for, sender=MyModel)
def my_model_post_processing(sender, **kwargs):
# do some unrelated logic...
logic = 'fun! '
#if something has changed... update any other field with the same id
cascade_update = MyModel.exclude(id=sender.id).filter(some_key=sender.some_key)
for c in cascade_update:
c.some_field = sender.some_field
c.save()
Disconnect the signal before calling save and then reconnect it afterwards:
post_save.disconnect(my_receiver_function, sender=MyModel)
instance.save()
post_save.connect(my_receiver_function, sender=MyModel)
Disconnecting a signal is not a DRY and consistent solution, such as using update() instead of save().
To bypass signal firing on your model, a simple way to go is to set an attribute on the current instance to prevent upcoming signals firing.
This can be done using a simple decorator that checks if the given instance has the 'skip_signal' attribute, and if so prevents the method from being called:
from functools import wraps
def skip_signal(signal_func):
#wraps(signal_func)
def _decorator(sender, instance, **kwargs):
if hasattr(instance, 'skip_signal'):
return None
return signal_func(sender, instance, **kwargs)
return _decorator
Based on your example, that gives us:
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=MyModel)
#skip_signal()
def my_model_post_save(sender, instance, **kwargs):
instance.some_field = my_value
# Here we flag the instance with 'skip_signal'
# and my_model_post_save won't be called again
# thanks to our decorator, avoiding any signal recursion
instance.skip_signal = True
instance.save()
Hope This helps.
A solution may be use update() method to bypass signal:
cascade_update = MyModel.exclude(
id=sender.id).filter(
some_key=sender.some_key).update(
some_field = sender.some_field )
"Be aware that the update() method is converted directly to an SQL statement. It is a bulk operation for direct updates. It doesn't run any save() methods on your models, or emit the pre_save or post_save signals"
You could move related objects update code into MyModel.save method. No playing with signal is needed then:
class MyModel(models.Model):
some_field = #
some_key = #
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs)
for c in MyModel.objects.exclude(id=self.id).filter(some_key=self.some_key):
c.some_field = self.some_field
c.save()
Here's the situation:
Let's say I have a model A in django. When I'm saving an object (of class A) I need to save it's fields into all other objects of this class. I mean I need every other A object to be copy of lat saved one.
When I use signals (post-save for example) I get a recursion (objects try to save each other I guess) and my python dies.
I men I expected that using .save() method on the same class in pre/post-save signal would cause a recursion but just don't know how to avoid it.
What do we do?
#ShawnFumo Disconnecting a signal is dangerous if the same model is saved elsewhere at the same time, don't do that !
#Aram Dulyan, your solution works but prevent you from using signals which are so powerful !
If you want to avoid recursion and keep using signals (), a simple way to go is to set an attribute on the current instance to prevent upcoming signals firing.
This can be done using a simple decorator that checks if the given instance has the 'skip_signal' attribute, and if so prevents the method from being called:
from functools import wraps
def skip_signal():
def _skip_signal(signal_func):
#wraps(signal_func)
def _decorator(sender, instance, **kwargs):
if hasattr(instance, 'skip_signal'):
return None
return signal_func(sender, instance, **kwargs)
return _decorator
return _skip_signal
We can now use it this way:
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=MyModel)
#skip_signal()
def my_model_post_save(sender, instance, **kwargs):
# you processing
pass
m = MyModel()
# Here we flag the instance with 'skip_signal'
# and my_model_post_save won't be called
# thanks to our decorator, avoiding any signal recursion
m.skip_signal = True
m.save()
Hope This helps.
This will work:
class YourModel(models.Model):
name = models.CharField(max_length=50)
def save_dupe(self):
super(YourModel, self).save()
def save(self, *args, **kwargs):
super(YourModel, self).save(*args, **kwargs)
for model in YourModel.objects.exclude(pk=self.pk):
model.name = self.name
# Repeat the above for all your other fields
model.save_dupe()
If you have a lot of fields, you'll probably want to iterate over them when copying them to the other model. I'll leave that to you.
Another way to handle this is to remove the listener while saving. So:
class Foo(models.Model):
...
def foo_post_save(instance):
post_save.disconnect(foo_post_save, sender=Foo)
do_stuff_toSaved_instance(instance)
instance.save()
post_save.connect(foo_post_save, sender=Foo)
post_save.connect(foo_post_save, sender=Foo)
say I've got:
class LogModel(models.Model):
message = models.CharField(max_length=512)
class Assignment(models.Model):
someperson = models.ForeignKey(SomeOtherModel)
def save(self, *args, **kwargs):
super(Assignment, self).save()
old_person = #?????
LogModel(message="%s is no longer assigned to %s"%(old_person, self).save()
LogModel(message="%s is now assigned to %s"%(self.someperson, self).save()
My goal is to save to LogModel some messages about who Assignment was assigned to. Notice that I need to know the old, presave value of this field.
I have seen code that suggests, before super().save(), retrieve the instance from the database via primary key and grab the old value from there. This could work, but is a bit messy.
In addition, I plan to eventually split this code out of the .save() method via signals - namely pre_save() and post_save(). Trying to use the above logic (Retrieve from the db in pre_save, make the log entry in post_save) seemingly fails here, as pre_save and post_save are two seperate methods. Perhaps in pre_save I can retrieve the old value and stick it on the model as an attribute?
I was wondering if there was a common idiom for this. Thanks.
A couple of months ago I found somewhere online a good way to do this...
class YourModel(models.Model):
def __init__(self, *args, **kwargs):
super(YourModel, self).__init__(*args, **kwargs)
self.original = {}
id = getattr(self, 'id', None)
for field in self._meta.fields:
if id:
self.original[field.name] = getattr(self, field.name, None)
else:
self.original[field.name] = None
Basically a copy of the model fields will get saved to self.original. You can then access it elsewhere in the model...
def save(self, *args, **kwargs):
if self.original['my_property'] != self.my_property:
# ...
It can be easily done with signals. There are, respectively a pre-save and post-save signal for every Django Model.
So I came up with this:
class LogModel(models.Model):
message = models.CharField(max_length=512)
class Assignment(models.Model):
someperson = models.ForeignKey(SomeOtherModel)
import weakref
_save_magic = weakref.WeakKeyDictionary()
#connect(pre_save, Assignment)
def Assignment_presave(sender, instance, **kwargs):
if instance.pk:
_save_magic[instance] = Assignment.objects.get(pk=instance.pk).someperson
#connect(post_save, Assignment)
def Assignment_postsave(sender, instance, **kwargs):
old = None
if instance in _save_magic:
old = _save_magic[instance]
del _save_magic[instance]
LogModel(message="%s is no longer assigned to %s"%(old, self).save()
LogModel(message="%s is now assigned to %s"%(instance.someperson, self).save()
What does StackOverflow think? Anything better? Any tips?