insert_country.py 1.59 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/env python3

"""
Script to insert the country data in the database

IT HAS TO BE RUN INSIDE ./manage.py shell
"""
import os
Florent Chehab's avatar
Florent Chehab committed
9
import pandas as pd
10

Florent Chehab's avatar
Florent Chehab committed
11
from rex.models.country import Country, Region
12

Florent Chehab's avatar
Florent Chehab committed
13
tmp = os.path.join(os.path.realpath(__file__), '../../assets/country.csv')
14
15
country_file_loc = os.path.abspath(tmp)

Florent Chehab's avatar
Florent Chehab committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
data = pd.read_csv(country_file_loc, sep=',', header=0,
                   dtype=object).fillna('')
data = data.drop(["Least Developed Countries (LDC)",
                  "Land Locked Developing Countries (LLDC)",
                  "Small Island Developing States (SIDS)",
                  "Developed / Developing Countries"],
                 axis=1)

r = [("Region Code", "Region Name"),
     ("Sub-region Code", "Sub-region Name"),
     ("Intermediate Region Code", "Intermediate Region Name"),
     ("ISO-alpha3 Code", "Country or Area")]


for index, row in data.iterrows():
    for i in range(len(r) - 1):
        r_type = r[i]
        region_code = row[r_type[0]]
        region_name = row[r_type[1]]
        if region_code is not '':
            # look for parent region
            parent = None
            if i > 0:
                parent_code = row[r[i - 1][0]]
                if parent_code is not '':
                    parent = Region.objects.get(pk=parent_code)
            region = Region(un_code=region_code,
                            name=region_name,
                            parent=parent)
            region.save()
        else:
            break
48

Florent Chehab's avatar
Florent Chehab committed
49
50
51
52
    c_code = row[r[3][0]]
    c_name = row[r[3][1]]
    c = Country(name=c_name, iso_alpha3_code=c_code, region=region)
    c.save()