city.py 1.12 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.db import models
2
from rest_framework import serializers
3
from backend.models.location import Country
4
from backend.models.my_model import MyModel, MyModelSerializer, MyModelVersionnedViewSet
Florent Chehab's avatar
Florent Chehab committed
5
6


7
class City(MyModel):
Florent Chehab's avatar
Florent Chehab committed
8
9
10
11
12
13
14
15
    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)


16
class CitySerializer(MyModelSerializer):
Florent Chehab's avatar
Florent Chehab committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    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__'


31
class CityViewSet(MyModelVersionnedViewSet):
Florent Chehab's avatar
Florent Chehab committed
32
33
    queryset = City.objects.all()  # pylint: disable=E1101
    serializer_class = CitySerializer