city.py 1.27 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
2
from django.db import models
from rest_framework import serializers, permissions
3
4
from backend.models.tools import DictModeViewSet
from backend.models.location import Country
Florent Chehab's avatar
Florent Chehab committed
5
6
7
8
9
10
11
12
13
14
15
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


# Data model based on : https://unstats.un.org/unsd/methodology/m49/overview/


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 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:
        model = City
        fields = '__all__'


class CityViewSet(DictModeViewSet):
    permission_classes = (permissions.DjangoModelPermissions,)
    queryset = City.objects.all()  # pylint: disable=E1101
    serializer_class = CitySerializer