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] - тип данных для преобразования
|
||||
|
||||
"""
|
||||
|
||||
card = {
|
||||
"Collection": {
|
||||
"dependencies": ("Country", ),
|
||||
"fields": {
|
||||
"Collections": {
|
||||
# нету аналогов для полей start и end
|
||||
"name": "title",
|
||||
"slug": "slug",
|
||||
}
|
||||
},
|
||||
"relations": {
|
||||
"country": "Country",
|
||||
"dependencies": ("Country", ),
|
||||
"fields": {
|
||||
"Collections": {
|
||||
# нету аналогов для полей start и end
|
||||
"name": "title",
|
||||
"slug": "slug",
|
||||
}
|
||||
},
|
||||
"relations": {
|
||||
"country": "Country",
|
||||
}
|
||||
},
|
||||
"Guide": {
|
||||
"dependencies": ("Collection", ),
|
||||
"fields": {
|
||||
|
|
@ -39,4 +38,4 @@ card = {
|
|||
}
|
||||
}
|
||||
|
||||
used_apps = ("location", )
|
||||
used_apps = ("location", )
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ NOTE: среди legacy таблиц совпадение для таблицы
|
|||
|
||||
card = {
|
||||
"Country": {
|
||||
"data_type": "dictionaries",
|
||||
"dependencies": None,
|
||||
"fields": {
|
||||
"Cities": {
|
||||
|
|
@ -22,6 +23,7 @@ card = {
|
|||
},
|
||||
|
||||
"Region": {
|
||||
"data_type": "dictionaries",
|
||||
"dependencies": ("Country", "Region"),
|
||||
"fields": {
|
||||
# нету аналога для поля name
|
||||
|
|
@ -36,6 +38,7 @@ card = {
|
|||
},
|
||||
|
||||
"City": {
|
||||
"data_type": "dictionaries",
|
||||
"dependencies": ("Country", "Region"),
|
||||
"fields": {
|
||||
"Cities": {
|
||||
|
|
@ -56,6 +59,7 @@ card = {
|
|||
|
||||
|
||||
"Address": {
|
||||
"data_type": "dictionaries",
|
||||
"dependencies": ("City",),
|
||||
"fields": {
|
||||
# нету аналога для поля number
|
||||
|
|
|
|||
|
|
@ -1,38 +1,32 @@
|
|||
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
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Transfer data between databases'
|
||||
|
||||
types = [
|
||||
"""Типы данных для трансфера
|
||||
ВНИМАНИЕ: первые буквы типов данных должны быть уникальны!
|
||||
"""
|
||||
DATA_TYPES = [
|
||||
'dictionaries',
|
||||
'keys'
|
||||
]
|
||||
|
||||
def handle(self, *args, **options):
|
||||
option = set(options.keys()) & set(self.types)
|
||||
print(option)
|
||||
if options['dictionaries']:
|
||||
self._transfer_objects()
|
||||
"""Находим включённую опцию путём пересечения множества типов данных и множества включённых опций"""
|
||||
data_type = list(set(option for option in options.keys() if options[option]) & set(self.DATA_TYPES))
|
||||
if len(data_type) != 1:
|
||||
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):
|
||||
for type in self.types:
|
||||
"""Добавляем опции к команде, основываясь на типах данных, определённых в DATA_TYPES"""
|
||||
for option_type in self.DATA_TYPES:
|
||||
parser.add_argument(
|
||||
f'-{type[:1]}',
|
||||
f'--{type}',
|
||||
f'-{option_type[:1]}',
|
||||
f'--{option_type}',
|
||||
action='store_true',
|
||||
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
|
||||
|
||||
def transfer_objects(app, transfer_card):
|
||||
print(app)
|
||||
for model, card in transfer_card.items():
|
||||
|
||||
def transfer_objects(data_type):
|
||||
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(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