sorting out some migration dependency issues
[plstackapi.git] / planetstack / model_policy.py
1 from django.db.models.signals import post_save
2 from django.dispatch import receiver
3 import pdb
4 from core.models import *
5 from dependency_walker import *
6 import model_policies
7
8 modelPolicyEnabled = True
9
10 def EnableModelPolicy(x):
11     global modelPolicyEnabled
12     modelPolicyEnabled = x
13
14 def update_dep(d, o):
15         if (d.updated < o.updated):
16                 d.save(update_fields=['updated'])
17         
18 def delete_if_inactive(d, o):
19         #print "Deleting %s (%s)"%(d,d.__class__.__name__)
20         d.delete()      
21         return
22
23 @receiver(post_save)
24 def post_save_handler(sender, instance, **kwargs):
25         if not modelPolicyEnabled:
26             return
27
28         sender_name = sender.__name__
29         policy_name = 'model_policy_%s'%sender_name
30         
31         if (not kwargs['update_fields']):
32                 # Automatic dirtying
33                 walk_inv_deps(update_dep, instance)
34
35                 try:
36                         policy_handler = getattr(model_policies, policy_name, None)
37                         if policy_handler is not None:
38                                 policy_handler.handle(instance)
39                 except:
40                         pass
41         elif 'deleted' in kwargs['update_fields']:
42                 walk_inv_deps(delete_if_inactive, instance)
43