I have several models that save log data to my database. I also have a “recent events” app and I would like to choose which models send data to the events app. I thought a decorator would be good for this, so I could just add it to the models I want:
@logger
class TemperatureLog(models.Model):
Date = models.DateTimeField(auto_now_add=True)
Device = models.ForeignKey(TemperatureDevice)
Data = models.PositiveIntegerField()
Here is the events model, Im using generic foreign keys:
class Event(models.Model):
Active = models.BooleanField()
Queue = models.BooleanField()
ContentType = models.ForeignKey(ContentType)
ObjectID = models.PositiveIntegerField()
Event = generic.GenericForeignKey('ContentType', 'ObjectID')
And here is the decorator:
def logger(event):
def wrap(*args, **kwargs):
from toolbox.event.models import Event
event(*args, **kwargs).save()
myid = event(*args, **kwargs).id
new = Event(Event=event.objects.get(id=myid))
if Event.objects.all().filter(Active=True).count() >= 25:
new.Queue = True
new.save()
else:
new.Active = True
new.save()
for item in Event.objects.all().filter(Queue=True):
item.Queue = False
item.Active = True
item.save()
if Event.objects.all().filter(Active=True).count() >= 25:
break
return event(*args, **kwargs)
return wrap
It works as it should, it creates the event instance and saves it. The problem that I have is that save() would be called twice. One in the decorator and the second in the actual code that collects the temperature logs (since I wont know ahead of time which apps will send events and which wont or if they might change in the future). So I wonder if there is a more elegant way to do this. I like the decorator approach since all I have to do is add it to the model class, but I am not very convinced of having save being called twice.
How about using post_save signal for all models