Add sort
Move dependencies to model Add data_type to model
This commit is contained in:
parent
ea427d6451
commit
673acb4bb9
|
|
@ -9,21 +9,20 @@ field[1] - название поля в таблице legacy
|
||||||
Опционально: field[2] - тип данных для преобразования
|
Опционально: field[2] - тип данных для преобразования
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
card = {
|
card = {
|
||||||
"Collection": {
|
"Collection": {
|
||||||
"dependencies": ("Country", ),
|
"dependencies": ("Country", ),
|
||||||
"fields": {
|
"fields": {
|
||||||
"Collections": {
|
"Collections": {
|
||||||
# нету аналогов для полей start и end
|
# нету аналогов для полей start и end
|
||||||
"name": "title",
|
"name": "title",
|
||||||
"slug": "slug",
|
"slug": "slug",
|
||||||
}
|
|
||||||
},
|
|
||||||
"relations": {
|
|
||||||
"country": "Country",
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"relations": {
|
||||||
|
"country": "Country",
|
||||||
|
}
|
||||||
|
},
|
||||||
"Guide": {
|
"Guide": {
|
||||||
"dependencies": ("Collection", ),
|
"dependencies": ("Collection", ),
|
||||||
"fields": {
|
"fields": {
|
||||||
|
|
@ -39,4 +38,4 @@ card = {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
used_apps = ("location", )
|
used_apps = ("location", )
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ NOTE: среди legacy таблиц совпадение для таблицы
|
||||||
|
|
||||||
card = {
|
card = {
|
||||||
"Country": {
|
"Country": {
|
||||||
|
"data_type": "dictionaries",
|
||||||
"dependencies": None,
|
"dependencies": None,
|
||||||
"fields": {
|
"fields": {
|
||||||
"Cities": {
|
"Cities": {
|
||||||
|
|
@ -22,6 +23,7 @@ card = {
|
||||||
},
|
},
|
||||||
|
|
||||||
"Region": {
|
"Region": {
|
||||||
|
"data_type": "dictionaries",
|
||||||
"dependencies": ("Country", "Region"),
|
"dependencies": ("Country", "Region"),
|
||||||
"fields": {
|
"fields": {
|
||||||
# нету аналога для поля name
|
# нету аналога для поля name
|
||||||
|
|
@ -36,6 +38,7 @@ card = {
|
||||||
},
|
},
|
||||||
|
|
||||||
"City": {
|
"City": {
|
||||||
|
"data_type": "dictionaries",
|
||||||
"dependencies": ("Country", "Region"),
|
"dependencies": ("Country", "Region"),
|
||||||
"fields": {
|
"fields": {
|
||||||
"Cities": {
|
"Cities": {
|
||||||
|
|
@ -56,6 +59,7 @@ card = {
|
||||||
|
|
||||||
|
|
||||||
"Address": {
|
"Address": {
|
||||||
|
"data_type": "dictionaries",
|
||||||
"dependencies": ("City",),
|
"dependencies": ("City",),
|
||||||
"fields": {
|
"fields": {
|
||||||
# нету аналога для поля number
|
# нету аналога для поля number
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,32 @@
|
||||||
from django.core.management.base import BaseCommand
|
from django.core.management.base import BaseCommand
|
||||||
from django.apps import apps
|
|
||||||
from os.path import exists
|
|
||||||
from importlib.machinery import SourceFileLoader
|
|
||||||
|
|
||||||
from transfer.utils import transfer_objects
|
from transfer.utils import transfer_objects
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
help = 'Transfer data between databases'
|
help = 'Transfer data between databases'
|
||||||
|
|
||||||
types = [
|
"""Типы данных для трансфера
|
||||||
|
ВНИМАНИЕ: первые буквы типов данных должны быть уникальны!
|
||||||
|
"""
|
||||||
|
DATA_TYPES = [
|
||||||
'dictionaries',
|
'dictionaries',
|
||||||
'keys'
|
|
||||||
]
|
]
|
||||||
|
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, **options):
|
||||||
option = set(options.keys()) & set(self.types)
|
"""Находим включённую опцию путём пересечения множества типов данных и множества включённых опций"""
|
||||||
print(option)
|
data_type = list(set(option for option in options.keys() if options[option]) & set(self.DATA_TYPES))
|
||||||
if options['dictionaries']:
|
if len(data_type) != 1:
|
||||||
self._transfer_objects()
|
print("You must set correct option!\r\nYou can get options list with \r\n\r\n\tmanage.py help transfer\r\n")
|
||||||
|
exit(1)
|
||||||
|
transfer_objects(data_type[0])
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
def add_arguments(self, parser):
|
||||||
for type in self.types:
|
"""Добавляем опции к команде, основываясь на типах данных, определённых в DATA_TYPES"""
|
||||||
|
for option_type in self.DATA_TYPES:
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
f'-{type[:1]}',
|
f'-{option_type[:1]}',
|
||||||
f'--{type}',
|
f'--{option_type}',
|
||||||
action='store_true',
|
action='store_true',
|
||||||
default=False,
|
default=False,
|
||||||
help=f'Transfer {type} objects'
|
help=f'Transfer {option_type} objects'
|
||||||
)
|
)
|
||||||
|
|
||||||
def _transfer_objects(self):
|
|
||||||
for app in apps.get_app_configs():
|
|
||||||
if exists(f"{app.path}/transfer.py"):
|
|
||||||
card_module = SourceFileLoader("transfer", f"{app.path}/transfer.py").load_module()
|
|
||||||
transfer_objects(app, card_module.card)
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,55 @@
|
||||||
|
from os.path import exists
|
||||||
|
from importlib.machinery import SourceFileLoader
|
||||||
|
from django.apps import apps
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
def transfer_objects(app, transfer_card):
|
|
||||||
print(app)
|
def transfer_objects(data_type):
|
||||||
for model, card in transfer_card.items():
|
models_list = {}
|
||||||
|
|
||||||
|
for app in apps.get_app_configs():
|
||||||
|
if exists(f"{app.path}/transfer.py"):
|
||||||
|
card_module = SourceFileLoader("transfer", f"{app.path}/transfer.py").load_module()
|
||||||
|
if not hasattr(card_module, "card") or len(card_module.card) < 1:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for model, card in card_module.card.items():
|
||||||
|
if "data_type" in card and data_type == card["data_type"]:
|
||||||
|
card['name'] = model
|
||||||
|
models_list[model] = card
|
||||||
|
|
||||||
|
if len(models_list) < 1:
|
||||||
|
print(f"Models with data type {data_type} not found in structure")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
models_list = sort_by_dependencies(models_list)
|
||||||
|
|
||||||
|
print(f"==========================\r\n{models_list}\r\n==========================\r\n")
|
||||||
|
|
||||||
|
for model, card in models_list.items():
|
||||||
print(model)
|
print(model)
|
||||||
print(f"\t{card}")
|
print(card)
|
||||||
|
|
||||||
|
|
||||||
|
def sort_by_dependencies(data):
|
||||||
|
"""Сначала мы сортируем модели по зависимостям в обратном порядке, используя сортировку вставкой"""
|
||||||
|
result = []
|
||||||
|
for model, card in data.items():
|
||||||
|
if "dependencies" in card and isinstance(card['dependencies'], tuple):
|
||||||
|
for model_dependency in result:
|
||||||
|
if model_dependency in card['dependencies']:
|
||||||
|
result.insert(result.index(model_dependency), model)
|
||||||
|
break
|
||||||
|
|
||||||
|
else:
|
||||||
|
result.append(model)
|
||||||
|
|
||||||
|
"""Затем мы создаём сортированный словарь из реверса получившегося результата"""
|
||||||
|
print(result)
|
||||||
|
|
||||||
|
result = OrderedDict(
|
||||||
|
[(model, data[model]) for model in reversed(result)]
|
||||||
|
)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user