diff options
author | Étienne Loks <etienne.loks@iggdrasil.net> | 2018-04-18 17:52:48 +0200 |
---|---|---|
committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2018-06-12 08:41:54 +0200 |
commit | 48046732fbbd307906c492344c886da5f713f06d (patch) | |
tree | df039068c6530250f1bcb2d147b00feafcd2a285 /ishtar_common/utils.py | |
parent | 4e6b1d4c2e4948d4269ff7c5734b94c15cb60a7e (diff) | |
download | Ishtar-48046732fbbd307906c492344c886da5f713f06d.tar.bz2 Ishtar-48046732fbbd307906c492344c886da5f713f06d.zip |
Manage groupment of towns with areas (refs #4060)
Diffstat (limited to 'ishtar_common/utils.py')
-rw-r--r-- | ishtar_common/utils.py | 63 |
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)) |