serializers.py 1.69 KB
Newer Older
1
2
# standard library imports
from __future__ import absolute_import, print_function
3
4
# core django imports
from django.core.serializers import serialize
5
6
7
8
# third party imports
from rest_framework import serializers
# imports from your apps
from housing.models import Building, Floor, Room
9
from accounts.models import Major
10
11
12
13


class BuildingSerializer(serializers.ModelSerializer):

14
15
16
17
18
19
20
    floors = serializers.SerializerMethodField('get_building_floors')

    def get_building_floors(self, building):
        floors = serialize('json', Floor.objects.filter(building=building),
                           fields=('number'))
        return floors

21
22
23
24
25
26
27
    class Meta:
        model = Building
        fields = ('name', 'neighbourhood', 'campus')


class FloorSerializer(serializers.ModelSerializer):

28
29
30
31
32
33
34
35
36
37
    building = serializers.SerializerMethodField('get_building_name')

    def get_building_name(self, floor):
        return floor.building.name

    def get_floor_rooms(self, floor):
        rooms = serialize('json', Room.objects.filter(floor=floor),
                          fields=('number'))
        return rooms

38
39
    class Meta:
        model = Floor
40
        fields = ('number', 'building')
41
42
43
44


class RoomSerializer(serializers.ModelSerializer):

45
46
47
48
49
50
51
52
53
    building = serializers.SerializerMethodField('get_building_name')
    floor = serializers.SerializerMethodField('get_floor_number')

    def get_building_name(self, room):
        return room.floor.building.name

    def get_floor_number(self, room):
        return room.floor.number

54
55
    class Meta:
        model = Room
56
57
58
59
60
61
62
63
        fields = ('number', 'floor', 'building')


class MajorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Major
        fields = ('name', )