Commit c612b5b6 authored by Florent Chehab's avatar Florent Chehab

Merge branch 'country_update' into 'master'

Modification de toute l'architecture de base

See merge request chehabfl/outgoing_rex!5
parents cd62298f a1ea0015
Pipeline #22085 passed with stages
in 1 minute and 43 seconds
release: python manage.py migrate
release: python manage.py createinitialrevisions
web: gunicorn general.wsgi
#OutGoing_REX_dev
pandas # usefull for reading csv but necessary for the app to work
requests
......@@ -150,6 +150,12 @@ _Migrez_ la base de donnée :
./manage.py migrate
```
_Initialisez_ les révisions:
```bash
./manage.py createinitialrevisions
```
_NB: cette opération (en plus de `./manage.py makemigrations` et de la précédente) est à faire à chaque fois que vous rajoutez/modifier un model._
_Collectez_ les éléments statistiques :
```bash
./manage.py collectstatic
......
Chargement des données initiales pour l'application
=====
[SECTION QUI VA ÉVOLUER]
Chargement des données des pays :
Pour charger des données dans l'application, tout se passe via l'API du site.
- Créer un superutilisateur :
```bash
./manage.py shell
./manage.py createsuperuser
```
Puis à l'intérieur de ce shell :
```python
%run ./rex/utils/insert_country.py
```
- Créer un token dans l'administration (pour l'administrateur que vous venez de créer).
**CE TOKEN DOIT RESTER SECRET**.
Pour les universitées, toujours à l'intérieur du shell `./manage.py shell` :
```python
%run ./rex/utils/insert_universities.py
```
\ No newline at end of file
- Lancer les scripts pour insérer les données :
```
./rex/utils/insert_country.py -t <Token> [-a <server adress>]
./rex/utils/insert_universities.py-t <Token> [-a <Adresse-de-l'API>]
```
from django.contrib import admin
from reversion_compare.admin import CompareVersionAdmin
from rex.models.university import University
from rex.models.country import Country
from rex.models.university import University, MainCampus
from rex.models.location import Country, Region, City
admin.site.register(University, CompareVersionAdmin)
admin.site.register(Country)
admin.site.register(Region)
admin.site.register(City)
admin.site.register(University, CompareVersionAdmin)
admin.site.register(MainCampus, CompareVersionAdmin)
"alpha-2","alpha-3"
"AF","AFG"
"AX","ALA"
"AL","ALB"
"DZ","DZA"
"AS","ASM"
"AD","AND"
"AO","AGO"
"AI","AIA"
"AQ","ATA"
"AG","ATG"
"AR","ARG"
"AM","ARM"
"AW","ABW"
"AU","AUS"
"AT","AUT"
"AZ","AZE"
"BS","BHS"
"BH","BHR"
"BD","BGD"
"BB","BRB"
"BY","BLR"
"BE","BEL"
"BZ","BLZ"
"BJ","BEN"
"BM","BMU"
"BT","BTN"
"BO","BOL"
"BQ","BES"
"BA","BIH"
"BW","BWA"
"BV","BVT"
"BR","BRA"
"IO","IOT"
"BN","BRN"
"BG","BGR"
"BF","BFA"
"BI","BDI"
"CV","CPV"
"KH","KHM"
"CM","CMR"
"CA","CAN"
"KY","CYM"
"CF","CAF"
"TD","TCD"
"CL","CHL"
"CN","CHN"
"CX","CXR"
"CC","CCK"
"CO","COL"
"KM","COM"
"CG","COG"
"CD","COD"
"CK","COK"
"CR","CRI"
"CI","CIV"
"HR","HRV"
"CU","CUB"
"CW","CUW"
"CY","CYP"
"CZ","CZE"
"DK","DNK"
"DJ","DJI"
"DM","DMA"
"DO","DOM"
"EC","ECU"
"EG","EGY"
"SV","SLV"
"GQ","GNQ"
"ER","ERI"
"EE","EST"
"ET","ETH"
"FK","FLK"
"FO","FRO"
"FJ","FJI"
"FI","FIN"
"FR","FRA"
"GF","GUF"
"PF","PYF"
"TF","ATF"
"GA","GAB"
"GM","GMB"
"GE","GEO"
"DE","DEU"
"GH","GHA"
"GI","GIB"
"GR","GRC"
"GL","GRL"
"GD","GRD"
"GP","GLP"
"GU","GUM"
"GT","GTM"
"GG","GGY"
"GN","GIN"
"GW","GNB"
"GY","GUY"
"HT","HTI"
"HM","HMD"
"VA","VAT"
"HN","HND"
"HK","HKG"
"HU","HUN"
"IS","ISL"
"IN","IND"
"ID","IDN"
"IR","IRN"
"IQ","IRQ"
"IE","IRL"
"IM","IMN"
"IL","ISR"
"IT","ITA"
"JM","JAM"
"JP","JPN"
"JE","JEY"
"JO","JOR"
"KZ","KAZ"
"KE","KEN"
"KI","KIR"
"KP","PRK"
"KR","KOR"
"KW","KWT"
"KG","KGZ"
"LA","LAO"
"LV","LVA"
"LB","LBN"
"LS","LSO"
"LR","LBR"
"LY","LBY"
"LI","LIE"
"LT","LTU"
"LU","LUX"
"MO","MAC"
"MK","MKD"
"MG","MDG"
"MW","MWI"
"MY","MYS"
"MV","MDV"
"ML","MLI"
"MT","MLT"
"MH","MHL"
"MQ","MTQ"
"MR","MRT"
"MU","MUS"
"YT","MYT"
"MX","MEX"
"FM","FSM"
"MD","MDA"
"MC","MCO"
"MN","MNG"
"ME","MNE"
"MS","MSR"
"MA","MAR"
"MZ","MOZ"
"MM","MMR"
"NA","NAM"
"NR","NRU"
"NP","NPL"
"NL","NLD"
"NC","NCL"
"NZ","NZL"
"NI","NIC"
"NE","NER"
"NG","NGA"
"NU","NIU"
"NF","NFK"
"MP","MNP"
"NO","NOR"
"OM","OMN"
"PK","PAK"
"PW","PLW"
"PS","PSE"
"PA","PAN"
"PG","PNG"
"PY","PRY"
"PE","PER"
"PH","PHL"
"PN","PCN"
"PL","POL"
"PT","PRT"
"PR","PRI"
"QA","QAT"
"RE","REU"
"RO","ROU"
"RU","RUS"
"RW","RWA"
"BL","BLM"
"SH","SHN"
"KN","KNA"
"LC","LCA"
"MF","MAF"
"PM","SPM"
"VC","VCT"
"WS","WSM"
"SM","SMR"
"ST","STP"
"SA","SAU"
"SN","SEN"
"RS","SRB"
"SC","SYC"
"SL","SLE"
"SG","SGP"
"SX","SXM"
"SK","SVK"
"SI","SVN"
"SB","SLB"
"SO","SOM"
"ZA","ZAF"
"GS","SGS"
"SS","SSD"
"ES","ESP"
"LK","LKA"
"SD","SDN"
"SR","SUR"
"SJ","SJM"
"SZ","SWZ"
"SE","SWE"
"CH","CHE"
"SY","SYR"
"TW","TWN"
"TJ","TJK"
"TZ","TZA"
"TH","THA"
"TL","TLS"
"TG","TGO"
"TK","TKL"
"TO","TON"
"TT","TTO"
"TN","TUN"
"TR","TUR"
"TM","TKM"
"TC","TCA"
"TV","TUV"
"UG","UGA"
"UA","UKR"
"AE","ARE"
"GB","GBR"
"US","USA"
"UM","UMI"
"UY","URY"
"UZ","UZB"
"VU","VUT"
"VE","VEN"
"VN","VNM"
"VG","VGB"
"VI","VIR"
"WF","WLF"
"EH","ESH"
"YE","YEM"
"ZM","ZMB"
"ZW","ZWE"
This diff is collapsed.
"University","lat","lon"
"Technische Universitat Ilmenau",50.6828446,10.9383699
"Universidad Del Salvador",-34.59941195,-58.392732040256
"Swinburne University Of Technology",-37.85240845,144.99182255
"Technische Universitat Graz",47.06817255,15.4497318287299
"Universiteit Gent",51.0225378,3.71068134989542
"Universidade Federal De Minas Gerais",-19.86868095,-43.962194217906
"Universidade Federal De Campina Grande",-7.05925115,-37.2744434555441
"Universidade Estadual De Campinas (Unicamp)",-22.8224781,-47.0642599309425
"Universidade Caxias Do Sul",-29.16253545,-51.1483650151909
"Pontificia Universidade Catolica Do Parana",-23.29907785,-51.2102693622486
"Universidade Federal Do Parana",-23.5984464,-51.6732887712978
"Universidade Tecnologica Federal Do Parana",-25.0521636,-50.131186381692
"Universidade Federal De Santa Catarina",-27.5823901,-48.5050400209765
"Universidade Federal De Itajuba",-22.4137971,-45.4502726
"Universidade Federal Da Paraiba",-6.7505593,-35.6454502176197
"Universidade Federal Juiz De Fora",-21.7768942,-43.3691810386558
"Universidad Estadual De Maringa",-23.77903,-53.3252683935028
"Universidade Federal De Pernambuco",-8.05254345,-34.9510286675945
"Universidade Federal De Rio De Janeiro",-22.2459542,-42.5232866424185
"Escola Politecnica Da Universidade De Sao Paulo",-23.5552106,-46.7310401128074
"Universidade Federal De Uberlandia",-18.941683,-48.2148699674138
"Technical University Of Sofia",42.6559773,23.35512261205
"Universidad Arturo Prat",-33.43531325,-70.662435711441
"Pontificia Universidad Catolica De Valparaiso",-33.0449276,-71.6067964701924
"Universidad De Valparaiso",-32.7414062,-70.7024233560544
"Universidad Tecnica Federico Santa Maria",-33.0354207,-71.5970503
"Escuela Colombiana De Ingenieria",4.78305195,-74.0442040297156
"Universidad Autonoma De Bucaramanga",7.1168832,-73.1051629
"Universidad Eafit",6.10464025,-75.4557833087589
"Pohang University Of Science And Technology",36.0172898,129.323920997982
"Hanyang University",37.5551257,127.0447098
"Kookmin University",37.61147915,126.996468815557
"Escuela Politecnica Nacional De Quito",-0.2101692,-78.4886323
"Universidad De Murcia",38.0147121,-1.1676358
"Universidad De Zaragoza",41.6836311,-0.885944249252812
"Oulu University Of Applied Sciences",65.00861805,25.4726477466852
"Tampere University Of Technology",61.44964205,23.8587746189096
"Universita Della Calabria",39.3614022,16.2263106
"Universita Di Bologna",44.49964345,11.354422008333
"Universita Degli Studi Di Salerno",40.75586365,14.7804889453213
"Universita Degli Studi Di Genova",44.4148861,8.9266707
"Politecnico Di Milano",45.4790288,9.23221040387672
"Universita Degli Studi Di Napoli Federico Ii",40.84526205,14.2512487738249
"Chiba Institute Of Technology",35.6888667,140.02117559587
"Chiba University",35.62786925,140.103465749158
"Tohoku University",38.2530945,140.8736593
"Universite Libanaise",33.8724848,35.5194311623001
"Université Saint-Esprit De Kaslik",33.98168505,35.6192920532997
"Universidad Autonoma De Aguascalientes",21.8812194,-102.2924759
"Universidad De Guanajuato",19.7242185,-101.2440472
"Universidad Anahuac Mayab",21.11060445,-89.6123220044136
"Instituto Politecnico Nacional",21.1358397,-86.8493286
"Universidad Iberoamericana",25.445315,-101.0046875
"Upaep",19.2818385,-98.4397356
"Instituto Tecnologico De Zacatepec",18.65203335,-99.1833987516266
"Norwegian University Of Science And Technology",63.4103583,10.4087418620805
"University Twente",52.2380139,6.8566761
"Agh - University Of Science And Technology",50.0657033,19.9189586670586
"Politechnika Krakowska",50.0717009,19.941563
"Universidade Da Beira Interior",40.2780936,-7.50834821105263
"City University Of Hong Kong",22.34000115,114.169702912423
"Technical University Of Kosice",48.73280395,21.244194264458
"Chalmers University Of Technology",57.6896523,11.9766811023544
"Lulea University Of Technology",65.61991265,22.1410701
"Ecole Polytechnique Federale De Lausanne",46.5186594,6.566561505148
"National Chiao Tung University",24.78676765,120.997244116807
"National Taiwan University Of Science And Technology",25.01350785,121.541707560048
"university","city","country","lat","lon"
"Technische Universitat Ilmenau","Ilmenau","DE",50.68386845,10.9329051768032
"Universidad Del Salvador","Buenos Aires","AR",-34.5562653,-58.730053914754
"Swinburne University Of Technology","Victoria","AU",-37.85240845,144.99182255
"Technische Universitat Graz","Graz","AT",47.05821,15.460195677136
"Universiteit Gent","Gent","BE",51.0450413,3.7255573
"Universidade Federal De Minas Gerais","Belo Horizonte","BR",-19.8718898,-43.9630925706377
"Universidade Federal De Campina Grande","Campina Grande","BR",-6.76287395,-38.2281578339701
"Universidade Estadual De Campinas (Unicamp)","Campinas-Sao Paulo","BR",-22.8224781,-47.0642599309425
"Universidade Caxias Do Sul","Caxias Do Sul","BR",-29.16253545,-51.1483650151909
"Pontificia Universidade Catolica Do Parana","Curitiba","BR",-23.29907785,-51.2102693622486
"Universidade Federal Do Parana","Curitiba","BR",-23.5984464,-51.6732887712978
"Universidade Tecnologica Federal Do Parana","Curitiba","BR",-25.0521636,-50.131186381692
"Universidade Federal De Santa Catarina","Florianópolis","BR",-27.6033738,-48.5224633956674
"Universidade Federal De Itajuba","Itajuba","BR",-22.4137971,-45.4502726
"Universidade Federal Da Paraiba","João Pessoa","BR",-6.7505593,-35.6454502176197
"Universidade Federal Juiz De Fora","Juiz De Fora","BR",-21.7768942,-43.3691810386558
"Universidad Estadual De Maringa","Maringa","BR",-23.77903,-53.3252683935028
"Universidade Federal De Pernambuco","Recife","BR",-8.05254345,-34.9510286675945
"Universidade Federal De Rio De Janeiro","Rio De Janeiro","BR",-22.2459542,-42.5232866424185
"Escola Politecnica Da Universidade De Sao Paulo","Sao Paulo","BR",-23.5552106,-46.7310401128074
"Universidade Federal De Uberlandia","Uberlandia","BR",-18.941683,-48.2148699674138
"Technical University Of Sofia","Sofia","BG",42.6559773,23.35512261205
"Universidad Arturo Prat","Iquique","CL",-23.6455954,-70.394657443203
"Pontificia Universidad Catolica De Valparaiso","Valparaiso","CL",-33.0449276,-71.6067964701924
"Universidad De Valparaiso","Valparaiso","CL",-32.7414062,-70.7024233560544
"Universidad Tecnica Federico Santa Maria","Valparaiso","CL",-33.03510935,-71.5952505079485
"Escuela Colombiana De Ingenieria","Bogota","CO",4.78305195,-74.0442040297156
"Universidad Autonoma De Bucaramanga","Bucaramanga","CO",7.1168832,-73.1051629
"Universidad Eafit","Medellin","CO",6.10464025,-75.4557833087589
"Pohang University Of Science And Technology","Pohang","KR",36.0172898,129.323920997982
"Hanyang University","Seoul","KR",37.5558418,127.0438918
"Kookmin University","Seoul","KR",37.61147915,126.996468815557
"Seoul National University Of Science And Technology Seoultech","Seoul","KR",37.6324854,127.079487800846
"Escuela Politecnica Nacional De Quito","Quito","EC",-0.21033215,-78.4900641291908
"Universidad De Murcia","Murcia","ES",38.0147121,-1.1676358
"Universidad De Zaragoza","Zaragoza","ES",41.6836311,-0.885944249252812
"Oulu University Of Applied Sciences","Oulu","FI",65.00861805,25.4726477466852
"Tampere University Of Technology","Tampere","FI",61.44964205,23.8587746189096
"Universita Della Calabria","Arcavacata","IT",39.3614022,16.2263106
"Universita Di Bologna","Bologna","IT",44.50134225,11.3591361693006
"Universita Degli Studi Di Salerno","Fisciano","IT",40.75586365,14.7804889453213
"Universita Degli Studi Di Genova","Genova","IT",44.4148861,8.9266707
"Politecnico Di Milano","Milan","IT",45.4790288,9.23221040387672
"Universita Degli Studi Di Napoli Federico Ii","Napoli","IT",40.84526205,14.2512487738249
"Chiba Institute Of Technology","Chiba","JP",35.6888667,140.02117559587
"Chiba University","Chiba","JP",35.62786925,140.103465749158
"Tohoku University","Sendai","JP",38.2530945,140.8736593
"Universite Libanaise","Beyrouth","LB",33.8724848,35.5194311623001
"Université Saint-Esprit De Kaslik","Kaslik","LB",33.98265035,35.620356742624
"Universidad Autonoma De Aguascalientes","Aguascalientes","MX",21.9142883,-102.32028877891
"Universidad De Guanajuato","Guanajuato","MX",19.7242185,-101.2440472
"Universidad Anahuac Mayab","Merida Yucatan","MX",21.11060445,-89.6123220044136
"Instituto Politecnico Nacional","Mexico","MX",19.4724472,-99.1373193
"Universidad Iberoamericana","Mexico","MX",25.445818,-101.0056267
"Upaep","Pueblar, Pue","MX",19.2818385,-98.4397356
"Instituto Tecnologico De Zacatepec","Zacatepec De Hidalgo","MX",18.65203335,-99.1833987516266
"Norwegian University Of Science And Technology","Trondheim","NO",63.4103583,10.4087418620805
"University Twente","Enschede","NL",52.2233862,6.88542315997116
"Agh - University Of Science And Technology","Cracovie","PL",50.0657033,19.9189586670586
"Politechnika Krakowska","Cracovie","PL",50.0754784,19.9089536
"Universidade Da Beira Interior","Covilhã","PT",40.2780936,-7.50834821105263
"City University Of Hong Kong","Hong Kong","HK",22.34000115,114.169702912423
"Technical University Of Kosice","Kosice","SK",48.73280395,21.244194264458
"Chalmers University Of Technology","Goteborg","SE",57.6896523,11.9766811023544
"Lulea University Of Technology","Lulea","SE",65.6170445,22.1370606335398
"Ecole Polytechnique Federale De Lausanne","Lausanne","CH",46.5186594,6.566561505148
"National Chiao Tung University","Hsinchu","TW",24.78676765,120.997244116807
"National Taiwan University Of Science And Technology","Taipei","TW",25.01350785,121.541707560048
# Generated by Django 2.0.3 on 2018-04-23 15:30
# Generated by Django 2.0.3 on 2018-04-25 14:48
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import rex.utils.friendly_path
......@@ -13,11 +14,42 @@ class Migration(migrations.Migration):
]
operations = [
migrations.CreateModel(
name='City',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('local_name', models.CharField(blank=True, max_length=200, null=True)),
('area', models.CharField(blank=True, max_length=200, null=True)),
],
),
migrations.CreateModel(
name='Country',
fields=[
('name', models.CharField(max_length=200)),
('iso_code', models.CharField(max_length=2, primary_key=True, serialize=False)),
('iso_alpha2_code', models.CharField(max_length=2, primary_key=True, serialize=False)),
],
),
migrations.CreateModel(
name='MainCampus',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200, null=True)),
('comment', models.TextField(blank=True, null=True)),
('lat', models.DecimalField(decimal_places=6, max_digits=10, validators=[django.core.validators.MinValueValidator(-85.05112878), django.core.validators.MaxValueValidator(85.05112878)])),
('lon', models.DecimalField(decimal_places=6, max_digits=10, validators=[django.core.validators.MinValueValidator(-180), django.core.validators.MaxValueValidator(180)])),
('city', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='rex.City')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Region',
fields=[
('name', models.CharField(max_length=200)),
('un_code', models.CharField(max_length=3, primary_key=True, serialize=False)),
('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='rex.Region')),
],
),
migrations.CreateModel(
......@@ -25,11 +57,19 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('acronym', models.CharField(max_length=20)),
('localization_lat', models.DecimalField(decimal_places=6, max_digits=10, validators=[django.core.validators.MinValueValidator(-85.05112878), django.core.validators.MaxValueValidator(85.05112878)])),
('localization_lon', models.DecimalField(decimal_places=6, max_digits=10, validators=[django.core.validators.MinValueValidator(-180), django.core.validators.MaxValueValidator(180)])),
('acronym', models.CharField(blank=True, max_length=20, null=True)),
('logo', models.ImageField(default='path/to/my/default/image.jpg', max_length=250, upload_to=rex.utils.friendly_path.friendly_path('uploads/universities/logos/', 'name'))),
('country', models.ForeignKey(on_delete='CASCADE', to='rex.Country')),
('main_campus', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='main_campus_of', to='rex.MainCampus')),
],
),
migrations.AddField(
model_name='country',
name='region',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='rex.Region'),
),
migrations.AddField(
model_name='city',
name='country',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='rex.Country'),
),
]
from .country import country # noqa: F401
from .location import location # noqa: F401
from .university import university # noqa: F401
from .module import module # noqa: F401
from .country import Country, CountryViewSet, CountrySerializer # noqa: F401
from django.db import models
from rest_framework import serializers, viewsets, permissions
class Country(models.Model):
name = models.CharField(max_length=200)
iso_code = models.CharField(primary_key=True, max_length=2)
class CountrySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Country
fields = ('name', 'iso_code', 'url')
class CountryViewSet(viewsets.ModelViewSet):
"""
retrieve:
Retourne un pays.
list:
Retourne une liste de pays.
create:
Créée un nouveau pays.
"""
permission_classes = (permissions.DjangoModelPermissions,)
queryset = Country.objects.all() # noqa: E1101
serializer_class = CountrySerializer
from .location import Country, CountrySerializer, CountryViewSet # noqa: F401
from .location import Region, RegionSerializer, RegionViewSet # noqa: F401
from .location import City, CitySerializer, CityViewSet # noqa: F401
from django.db import models
from rest_framework import serializers, viewsets, permissions
# Data model based on : https://unstats.un.org/unsd/methodology/m49/overview/
class Region(models.Model):
name = models.CharField(max_length=200)
un_code = models.CharField(primary_key=True, max_length=3)
parent = models.ForeignKey(
'self', on_delete=models.SET_NULL, null=True, blank=True)
def r_type(self):
p = 0
region = self
while region.parent is not None:
p += 1
region = region.parent
if p is 0:
return "main"
elif p is 1:
return "sub"
elif p is 2:
return "inter"
else:
raise Exception("Impossible case found")
class Country(models.Model):
name = models.CharField(max_length=200)
iso_alpha2_code = models.CharField(primary_key=True, max_length=2)
region = models.ForeignKey(
Region, on_delete=models.PROTECT, null=True, blank=True)
def get_regions(self):
regions = [None] * 3
regions.append(self.region)
while regions[-1] is not None and regions[-1].parent is not None:
regions.append(regions[-1].parent)
regions = regions[::-1]
return regions[0:3]
class City(models.Model):
name = models.CharField(max_length=200)
local_name = models.CharField(max_length=200, null=True, blank=True)
# We add an area to distinguish similarly named cities
# in a country
area = models.CharField(max_length=200, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.PROTECT)
"""
API RELATED STUFF BELLOW
"""
class CountrySerializer(serializers.ModelSerializer):
regions = serializers.SerializerMethodField()
def get_regions(self, obj):
regions = obj.get_regions()
def get_info(i):
r = regions[i]
r_code = r.un_code if r is not None else None
return {"code": r_code,
"url": self.get_region_url(regions[i])}
res = {}
res["main"] = get_info(0)
res["sub"] = get_info(1)
res["inter"] = get_info(2)
return res
def get_region_url(self, region):
if region is None:
return None
return serializers.HyperlinkedRelatedField(
view_name='country-detail',
read_only=True) \
.get_url(region, view_name='region-detail',
request=self.context['request'], format=None)
class Meta:
model = Country
fields = ('name', 'iso_alpha2_code',
'region', 'regions')
class DictModeViewSet(viewsets.ModelViewSet):
"""
ViewSet that renders data as dict with keys corresponding to the model
primary key. Instead of list.
"""
def list(self, request, *args, **kwargs):
response = super(viewsets.ModelViewSet, self).list( # pylint: disable=E1003
request, *args, **kwargs) # call the original 'list'
pk_attr_name = self.serializer_class.Meta.model._meta.pk.name
response.data = {
d[pk_attr_name]: d for d in response.data
}
return response
class CountryViewSet(DictModeViewSet):
permission_classes = (permissions.DjangoModelPermissions,)
queryset = Country.objects.all() # pylint: disable=E1101
serializer_class = CountrySerializer
class RegionSerializer(serializers.ModelSerializer):
parent_url = serializers.SerializerMethodField()
region_type = serializers.SerializerMethodField()
def get_parent_url(self, obj):
if obj.parent is None:
return None
return serializers.HyperlinkedRelatedField(
view_name='country-detail',
read_only=True) \
.get_url(obj.parent, view_name='region-detail',
request=self.context['request'], format=None)
def get_region_type(self, obj):
return obj.r_type()
class Meta:
model = Region
fields = ('name', 'un_code', 'parent', 'parent_url', 'region_type')
class RegionViewSet(DictModeViewSet):
permission_classes = (permissions.DjangoModelPermissions,)
queryset = Region.objects.all() # pylint: disable=E1101
serializer_class = RegionSerializer
class CitySerializer(serializers.ModelSerializer):
country_url = serializers.SerializerMethodField()
def get_country_url(self, obj):
return serializers.HyperlinkedRelatedField(
view_name='country-detail',
read_only=True) \
.get_url(obj.country, view_name='country-detail',
request=self.context['request'], format=None)
class Meta: