|
1 | | -from django.core.management.base import BaseCommand, CommandError |
2 | | -import __future__ |
| 1 | +from django.core.management.base import BaseCommand |
3 | 2 | from ModelTracker.models import History |
4 | | -import datetime |
5 | | -from django.apps import apps |
6 | | -def getModel(table_name): |
7 | | - return next((m for m in apps.get_models() if m._meta.db_table==table_name), None) |
| 3 | + |
8 | 4 |
|
9 | 5 | class Command(BaseCommand): |
10 | 6 | help = 'Restore Object to old status' |
11 | 7 |
|
12 | 8 | def add_arguments(self, parser): |
13 | 9 | parser.add_argument('--id', nargs='?', type=str,default=None) |
14 | | - parser.add_argument("--state",type=str,nargs='?',default="new") |
| 10 | + # parser.add_argument("--state",type=str,nargs='?',default="new") |
15 | 11 | parser.add_argument("--user",type=str,nargs='?',default="CLI") |
| 12 | + |
| 13 | + |
16 | 14 | def handle(self, *args, **options): |
17 | 15 | if not options.get("id",None): |
18 | 16 | print ("Change ID is needed") |
19 | 17 | exit(1) |
20 | | - print (options) |
| 18 | + |
21 | 19 | h = History.objects.get(id=int(options["id"])) |
22 | | - model = getModel(h.table) |
23 | | - if model == None: |
24 | | - print("Can't find the Model") |
25 | | - exit(2) |
26 | | - d=[f.name for f in model._meta.get_fields()] |
27 | | - if options["state"]=="old": state=h.old_state |
28 | | - else: state=h.new_state |
29 | | - keys2del=[] |
30 | | - for key in state: |
31 | | - if (key.startswith("_") and "_cache" in key) or (key not in d and not ("_id" in key and key[:-3] in d)): |
32 | | - keys2del.append(key) |
33 | | - if type(state[key])==type({}): |
34 | | - if state[key].get("_type",None) == "datetime": |
35 | | - state[key]=datetime.datetime.strptime(state[key]["value"],"%Y-%m-%d %H:%M:%S") |
36 | | - elif state[key].get("_type",None) == "date": |
37 | | - state[key]=datetime.datetime.strptime(state[key]["value"],"%Y-%m-%d") |
38 | | - for key in keys2del: |
39 | | - del state[key] |
40 | | - |
41 | | - print(state) |
42 | | - m=model(**state) |
| 20 | + m = h.get_object() |
43 | 21 | m.save(options["user"],event_name="Restore Record to %s (%s)"%(options["id"],options["state"])) |
44 | 22 |
|
45 | 23 |
|
|
0 commit comments