summaryrefslogtreecommitdiff
path: root/ishtar_common/utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'ishtar_common/utils.py')
-rw-r--r--ishtar_common/utils.py63
1 files changed, 63 insertions, 0 deletions
diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py
index 983ec5830..b03e794d0 100644
--- a/ishtar_common/utils.py
+++ b/ishtar_common/utils.py
@@ -417,3 +417,66 @@ def get_field_labels_from_path(model, path):
else:
labels.append(key)
return labels
+
+
+def create_default_areas(models=None):
+ # can be used on migrations if models are provided
+ if not models:
+ from ishtar_common.models import Area, Town, Department, State
+ else:
+ Area = models['area']
+ Town = models['town']
+ Department = models['department']
+ State = models['state']
+
+ areas = {}
+
+ idx = 0
+ for state in State.objects.all():
+ slug = 'state-' + slugify(state.label)
+ area, created = Area.objects.get_or_create(
+ txt_idx=slug, defaults={'label': state.label})
+ areas['state-{}'.format(state.pk)] = area
+ if created:
+ idx += 1
+ print("\n* {} state areas added".format(idx))
+
+ idx, idx2 = 0, 0
+ for dep in Department.objects.all():
+ slug = 'dep-' + slugify(dep.label)
+ area, created = Area.objects.get_or_create(
+ txt_idx=slug, defaults={'label': dep.label})
+ areas['dep-' + dep.number] = area
+ if created:
+ idx += 1
+ if not dep.state_id:
+ continue
+ state_slug = 'state-{}'.format(dep.state_id)
+ if state_slug not in areas:
+ continue
+ if area.parent and area.parent.pk == areas[state_slug].pk:
+ continue
+ idx2 += 1
+ area.parent = areas[state_slug]
+ area.save()
+ print(
+ "* {} department areas added with {} associations to state".format(
+ idx, idx2)
+ )
+
+ idx = 0
+ for town in Town.objects.all():
+ if not town.numero_insee or len(town.numero_insee) != 5:
+ continue
+ code_dep = 'dep-' + town.numero_insee[:2]
+ code_dep_dom = 'dep-' + town.numero_insee[:3]
+ if code_dep in areas:
+ if not areas[code_dep].towns.filter(pk=town.pk).count():
+ areas[code_dep].towns.add(town)
+ idx += 1
+ elif code_dep_dom in areas:
+ if not areas[code_dep_dom].towns.filter(pk=town.pk).count():
+ areas[code_dep_dom].towns.add(town)
+ idx += 1
+
+ print("* {} town associated to department area".format(idx))