poste
[auf_rh_dae.git] / project / dae / management / commands / dae.py
1 # -*- encoding: utf-8 -*-
2
3 import codecs
4 from django.core.management.base import BaseCommand
5 from project.dae import models as dae
6 from project.rh import models as rh
7
8 class Command(BaseCommand):
9
10 def handle(self, *args, **options):
11
12 self.stdout = codecs.getwriter('utf8')(self.stdout)
13
14 if len(args) != 2:
15 self.stdout.write("dae <modele> <id>\n")
16 return
17
18 classname = args[0]
19 klass = getattr(dae, classname, None)
20 if klass is None:
21 self.stdout.write("Le modèle %s n'existe pas dans DAE.\n" % classname)
22
23 id = int(args[1])
24 try:
25 obj = klass.objects.get(id=id)
26 except:
27 self.stdout.write("L'id %s n'existe pas pour le modèle %s dans DAE.\n" % \
28 (id, classname))
29 return
30
31
32 def duplicate(obj, level=0, skip=()):
33
34 klass = getattr(rh, obj.__class__.__name__)
35 copy = klass()
36
37 indent = " "*level*4
38 self.stdout.write(u"\n%s [%s] %s" % (indent, str(obj.__class__),
39 obj))
40
41 self.stdout.write(u"\n*** SKIP: %s ***" % (", ".join(skip)))
42
43 for f in [f for f in obj._meta.fields if f.name not in skip]:
44 value = getattr(obj, f.name)
45 self.stdout.write(u"\n%s * %s: %s" % (indent, f.name, value))
46 setattr(copy, f.name, value)
47
48 for obj_composition in obj._meta._related_objects_cache:
49 app_label, dummy = obj_composition.name.split(':')
50 field_name = obj_composition.field.rel.related_name
51 if field_name in skip:
52 continue
53 if app_label == obj._meta.app_label:
54 try:
55 children = getattr(obj, field_name)
56 self.stdout.write(u"\n%s + [%s] %s" % (indent,
57 app_label, field_name))
58 except:
59 # no reverse relation
60 #print "%s %s %s" % (indent, obj_composition, field_name)
61 continue
62 for child in children.all():
63 extra_skip = []
64
65 for f in child._meta.fields:
66 if getattr(child, f.name) == obj:
67 extra_skip.append(f.name)
68
69 child_copy = duplicate(child, level+1, skip + extra_skip)
70 copy.save()
71 setattr(child_copy, "%s_id" % extra_skip[0], copy.id)
72 child_copy.save()
73 return copy
74
75 copy = duplicate(obj, skip=['id', 'dae_dossiers', ])
76 print copy.__class__
77 print copy.id
78