class SiteSerializer(DynamicFieldsMixin, serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='apiv2:site-detail') geometry = geo_serializers.GeometryField(read_only=True, source="geom_transformed", precision=7) class Meta: model = outdoor_models.Site fields = ( 'id', 'geometry', 'url', 'structure', 'name', 'practice', 'description', 'description_teaser', 'ambiance', 'advice', 'period', 'labels', 'themes', 'portal', 'source', 'information_desks', 'web_links', 'eid', 'orientation', 'wind', )
class TrekListSerializer(TrekBaseSerializer): first_picture = serializers.ReadOnlyField( source='resized_picture_mobile') geometry = geo_serializers.GeometryField( read_only=True, precision=7, source='start_point', ) class Meta(TrekBaseSerializer.Meta): fields = ( 'id', 'pk', 'first_picture', 'name', 'departure', 'accessibilities', 'route', 'departure_city', 'difficulty', 'practice', 'themes', 'length', 'geometry', 'districts', 'cities', 'duration', 'ascent', 'descent', )
class KRWAreaSerializer(gis_serializers.GeoFeatureModelSerializer): area = gis_serializers.GeometryField() class Meta: model = models.Locatie fields = ('id', 'loc_id', 'loc_oms', 'krw_color', 'area') geo_field = 'area'
class MapPolygonSerializer(gis_serializers.GeoFeatureModelSerializer): latitude = serializers.DecimalField(source='mappolygon.lat', max_digits=18, decimal_places=15) longitude = serializers.DecimalField(source='mappolygon.lon', max_digits=18, decimal_places=15) field1 = serializers.CharField(source='mappolygon.field1') field2 = serializers.CharField(source='mappolygon.field2') mpoly = gis_serializers.GeometryField(source='mappolygon.mpoly') tags = serializers.SerializerMethodField(get_function('get_tags')) def get_tags(self, mappolygon): # build nested distinct list return Tag.objects.filter(approved=True, tagindiv__mapelement=mappolygon) \ .distinct('id', 'tag').values_list('tag', flat=True) class Meta: id_field = False geo_field = 'mpoly' model = MapPolygon fields = ('id', 'dataset', 'remote_id', 'name', 'latitude', 'longitude', 'field1', 'field2', 'tags')
class RoutingSerializer(serializers.Serializer): geom = geo_serializers.GeometryField( help_text=_("A linestring with ordered waypoints.")) callback_id = serializers.CharField( required=False, help_text=_("Optional callback id to match with your request.")) route = serializers.JSONField( read_only=True, help_text=_("All features used, in geojson format.")) way = geo_serializers.GeometryField( read_only=True, help_text=_("Routed way, as Linestring."), precision=6) def validate_geom(self, value): if not isinstance(value, LineString): raise ValidationError(_("Geometry should be a LineString object.")) value.srid = app_settings.INTERNAL_GEOMETRY_SRID return value
class TrekListSerializer(TrekBaseSerializer): first_picture = serializers.SerializerMethodField(read_only=True) geometry = geo_serializers.GeometryField( read_only=True, precision=7, source='start_point', ) def get_first_picture(self, obj): root_pk = self.context.get('root_pk') or obj.pk return obj.resized_picture_mobile(root_pk) class Meta(TrekBaseSerializer.Meta): fields = ( 'id', 'pk', 'first_picture', 'name', 'departure', 'accessibilities', 'route', 'departure_city', 'difficulty', 'practice', 'themes', 'length', 'geometry', 'districts', 'cities', 'duration', 'ascent', 'descent', )
class TouristicContentListSerializer( geo_serializers.GeoFeatureModelSerializer): geometry = geo_serializers.GeometryField(read_only=True, precision=7, source='geom2d_transformed') reservation_system = rest_serializers.ReadOnlyField( source='reservation_system.name', default="") pictures = rest_serializers.SerializerMethodField(read_only=True) def get_pictures(self, obj): if not obj.resized_pictures: return [] first_picture = obj.resized_pictures[0][0] thdetail_first = obj.resized_pictures[0][1] return [{ 'author': first_picture.author, 'title': first_picture.title, 'legend': first_picture.legend, 'url': os.path.join('/', str(self.context['root_pk']), settings.MEDIA_URL[1:], thdetail_first.name), }] class Meta: model = tourism_models.TouristicContent id_field = 'pk' geo_field = 'geometry' fields = ('id', 'pk', 'name', 'description', 'description_teaser', 'category', 'themes', 'contact', 'email', 'website', 'practical_info', 'pictures', 'type1', 'type2', 'approved', 'reservation_id', 'reservation_system', 'geometry')
class TouristicEventListSerializer( geo_serializers.GeoFeatureModelSerializer): geometry = geo_serializers.GeometryField(read_only=True, precision=7, source='geom2d_transformed') pictures = rest_serializers.SerializerMethodField(read_only=True) def get_pictures(self, obj): if not obj.resized_pictures: return [] first_picture = obj.resized_pictures[0][0] thdetail_first = obj.resized_pictures[0][1] return [{ 'author': first_picture.author, 'title': first_picture.title, 'legend': first_picture.legend, 'url': os.path.join('/', str(self.context['root_pk']), settings.MEDIA_URL[1:], thdetail_first.name), }] class Meta: model = tourism_models.TouristicEvent id_field = 'pk' geo_field = 'geometry' fields = ('id', 'pk', 'name', 'description_teaser', 'description', 'themes', 'pictures', 'begin_date', 'end_date', 'duration', 'meeting_point', 'meeting_time', 'contact', 'email', 'website', 'organizer', 'speaker', 'type', 'accessibility', 'participant_number', 'booking', 'target_audience', 'practical_info', 'approved', 'geometry')
class DistrictsSerializer(serializers.ModelSerializer): geometry = geo_serializers.GeometryField(read_only=True, source="geom", precision=7) class Meta: model = zoning_models.District fields = ('id', 'geometry', 'name', 'published')
class CitySerializer(serializers.ModelSerializer): geom = geo_serializers.GeometryField(read_only=True, source="geom2d_transformed", precision=7) class Meta: model = zoning_models.City fields = ('code', 'name', 'published', 'geom')
class GeneratedGeo3DSerializer(BaseGeoJSONSerializer, base_serializer_class): geometry = geo_serializers.GeometryField( read_only=True, source='geom3d_transformed', precision=7) class Meta(BaseGeoJSONSerializer.Meta, base_serializer_class.Meta): pass
class Base3DSerializer(object): """ Mixin used to replace geom with geom_3d field """ geometry = geo_serializers.GeometryField(read_only=True) def get_geometry(self, obj): return obj.geom3d_transformed
class CitySerializer(serializers.ModelSerializer): geometry = geo_serializers.GeometryField(read_only=True, source="geom", precision=7) id = serializers.ReadOnlyField(source='code') class Meta: model = zoning_models.City fields = ('id', 'geometry', 'name', 'published')
class LocatieSerializer(gis_serializers.GeoFeatureModelSerializer): geo_punt_2 = gis_serializers.GeometryField(source='geo_punt2') geo_punt_1 = gis_serializers.GeometryField(source='geo_punt1') meet_status_id = serializers.IntegerField( read_only=True, source='meet_status.id') meet_status_naam = serializers.CharField( read_only=True, source='meet_status.naam') class Meta: model = models.Locatie fields = ( 'id', 'loc_id', 'loc_oms', 'geo_punt_2', 'waterlichaam', 'watertype', 'status_krw', 'meet_status_id', 'meet_status_naam' ) geo_field = 'geo_punt_1'
class SensitiveAreaSerializer(DynamicFieldsMixin, serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='apiv2:sensitivearea-detail') name = serializers.SerializerMethodField(read_only=True) elevation = serializers.SerializerMethodField(read_only=True) description = serializers.SerializerMethodField(read_only=True) period = serializers.SerializerMethodField(read_only=True) practices = serializers.SerializerMethodField(read_only=True) info_url = serializers.URLField(source='species.url') structure = serializers.CharField(source='structure.name') create_datetime = serializers.DateTimeField(source='date_insert') update_datetime = serializers.DateTimeField(source='date_update') geometry = geo_serializers.GeometryField(read_only=True, source="geom_transformed", precision=7) species_id = serializers.SerializerMethodField(read_only=True) kml_url = serializers.SerializerMethodField(read_only=True) def get_name(self, obj): return get_translation_or_dict('name', self, obj.species) def get_description(self, obj): return get_translation_or_dict('description', self, obj) def get_period(self, obj): return [ getattr(obj.species, 'period{:02}'.format(p)) for p in range(1, 13) ] def get_practices(self, obj): return obj.species.practices.values_list('id', flat=True) def get_elevation(self, obj): return obj.species.radius def get_species_id(self, obj): if obj.species.category == sensitivity_models.Species.SPECIES: return obj.species.id return None def get_kml_url(self, obj): url = reverse('sensitivity:sensitivearea_kml_detail', kwargs={ 'lang': get_language(), 'pk': obj.pk }) return build_url(self, url) class Meta: model = sensitivity_models.SensitiveArea fields = ('id', 'contact', 'create_datetime', 'description', 'elevation', 'geometry', 'info_url', 'kml_url', 'name', 'period', 'practices', 'published', 'species_id', 'structure', 'update_datetime', 'url')
class ProjectSerializer(serializers.ModelSerializer): timezone = serializers.CharField(required=False) centroid = serializers_gis.GeometryField(required=False, read_only=True) extent = serializers.ListField(required=False, read_only=True) dataset_count = serializers.IntegerField(required=False, read_only=True) site_count = serializers.IntegerField(required=False, read_only=True) record_count = serializers.IntegerField(required=False, read_only=True) class Meta: model = Project fields = '__all__'
class ExtensibleNodeSerializer(DynamicRelationshipsMixin, geoserializers.GeoModelSerializer): """ node detail """ user = serializers.Field(source='user.username') status = serializers.Field(source='status.slug') geometry = geoserializers.GeometryField(label=_('coordinates')) layer_name = serializers.Field(source='layer.name') access_level = serializers.Field(source='get_access_level_display') relationships = serializers.SerializerMethodField('get_relationships') # this is needed to avoid adding stuff to DynamicRelationshipsMixin _relationships = {}
class SensitiveAreaSerializer(TranslatedModelSerializer): species = SpeciesSerializer() geometry = geo_serializers.GeometryField(read_only=True, source="geom2d_transformed", precision=7) kml_url = rest_serializers.SerializerMethodField(read_only=True) def get_kml_url(self, obj): return reverse('sensitivity:sensitivearea_kml_detail', kwargs={'lang': get_language(), 'pk': obj.pk}) class Meta: model = sensitivity_models.SensitiveArea geo_field = 'geometry' fields = ('id', 'species', 'description', 'contact', 'published', 'publication_date', 'kml_url', 'geometry')
class PartnerExportRegionListSerializer(serializers.ModelSerializer): export_formats = serializers.ListField() feature_selection = serializers.CharField() simplified_geom = geo_serializers.GeometryField(required=False) name = serializers.CharField() class Meta: # noqa model = PartnerExportRegion fields = ('id', 'feature_selection', 'schedule_period', 'schedule_hour', 'export_formats', 'name', 'last_run', 'next_run', 'simplified_geom', 'job_uid', 'last_size','group_name')
class ExtensibleNodeSerializer(DynamicRelationshipsMixin, HStoreSerializer): """ node detail """ layer = serializers.SlugRelatedField(slug_field='slug', queryset=Layer.objects.all()) layer_name = serializers.ReadOnlyField(source='layer.name') user = serializers.SlugRelatedField(slug_field='username', read_only=True) status = serializers.SlugRelatedField(slug_field='slug', read_only=True) geometry = geoserializers.GeometryField(label=_('coordinates')) access_level = serializers.ReadOnlyField(source='get_access_level_display') relationships = serializers.SerializerMethodField() # this is needed to avoid adding stuff to DynamicRelationshipsMixin _relationships = {}
class RegionSerializer(gis_serializers.GeoFeatureModelSerializer): creator = rest_serializers.ReadOnlyField( source='creator.username', help_text='Vendor who created the region') name = rest_serializers.CharField(max_length=255, help_text='Name of region') area = gis_serializers.GeometryField( help_text='GeoJSON polygon defining region') class Meta: model = Region geo_field = 'area' fields = ('id', 'uuid', 'name', 'price', 'creator')
class TouristicContentListSerializer(DynamicFieldsMixin, serializers.ModelSerializer): url = HyperlinkedIdentityField( view_name='apiv2:touristiccontent-detail') category = TouristicContentCategorySerializer() geometry = geo_serializers.GeometryField(read_only=True, source="geom2d_transformed", precision=7) class Meta: model = tourism_models.TouristicContent fields = ('id', 'url', 'description_teaser', 'description', 'category', 'approved', 'geometry')
class ExtentSpatialSerializer(serializers.Serializer): # pylint: disable=abstract-method extent_geometry = gis_serializers.GeometryField() def to_representation(self, instance): ret = super().to_representation(instance) # handle empty field if instance.extent_geometry is None: ret["bbox"] = {"bbox": [[]]} else: bbox = GEOSGeometry(instance.extent_geometry).extent bbox = list(bbox) ret["bbox"] = {"bbox": [bbox]} return ret["bbox"]
class ExtensibleNodeSerializer(DynamicRelationshipsMixin, geoserializers.GeoModelSerializer): """ node detail """ user = serializers.Field(source='user.username') status = serializers.Field(source='status.slug') geometry = geoserializers.GeometryField(label=_('coordinates')) layer_name = serializers.Field(source='layer.name') access_level = serializers.Field(source='get_access_level_display') relationships = serializers.SerializerMethodField('get_relationships') # relationships work this way: # to add a new relationship, add a new key # the value must be a tuple in which the first element is the view name (as specified in urls.py) # and the second must be the lookup field, usually slug or id/pk _relationships = { 'images': ('api_node_images', 'slug'), }
class HDXExportRegionListSerializer(serializers.ModelSerializer): # noqa """ The list serializer does not expose the Geom, as it can be large.""" export_formats = serializers.ListField() dataset_prefix = serializers.CharField() feature_selection = serializers.CharField() simplified_geom = geo_serializers.GeometryField(required=False) name = serializers.CharField() buffer_aoi = serializers.BooleanField() class Meta: # noqa model = HDXExportRegion fields = ('id', 'dataset_prefix', 'datasets', 'feature_selection', 'schedule_period', 'schedule_hour', 'export_formats', 'locations', 'name', 'last_run', 'next_run', 'simplified_geom', 'dataset_prefix', 'job_uid', 'license', 'subnational', 'extra_notes', 'is_private', 'buffer_aoi', 'last_size')
class PathSerializer(DynamicFieldsMixin, serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='apiv2:trek-detail') geometry = geo_serializers.GeometryField(read_only=True, source="geom3d_transformed", precision=7) length_2d = serializers.SerializerMethodField(read_only=True) length_3d = serializers.SerializerMethodField(read_only=True) def get_length_2d(self, obj): return round(obj.length_2d_m, 1) def get_length_3d(self, obj): return round(obj.length_3d_m, 1) class Meta: model = core_models.Path fields = ('id', 'comments', 'geometry', 'length_2d', 'length_3d', 'name', 'url')
class PinDetailSerializer(serializers.ModelSerializer): coords = geoserializers.GeometryField(label=('coordinates')) keywords = KeywordSerializer(many=True) images = ImageSerializer(many=True) retweetcounts = RetweetCountSerializer(many=True) facebookcounts = FacebookCountSerializer(many=True) # def category_map(self, article): # return { # 'Science': 'science', # 'Health': 'health', # 'Job Market': 'economy', # 'World': 'world', # 'Workplace': 'conflict' # }.get(article.articlecategory, 'world') class Meta: model = Article fields = ('pk', 'date', 'coords', 'headline', 'abstract', 'byline', 'url', 'category', 'retweetcount', 'sharecount', 'keywords', 'retweetcounts', 'facebookcounts', 'images') geo_field = 'coords'
class POIListSerializer(geo_serializers.GeoFeatureModelSerializer): pictures = serializers.SerializerMethodField(read_only=True) geometry = geo_serializers.GeometryField(read_only=True, precision=7, source='geom2d_transformed') type = serializers.ReadOnlyField(source='type.pk') def get_pictures(self, obj): serialized = [] for picture, thdetail in obj.resized_pictures: serialized.append({ 'author': picture.author, 'title': picture.title, 'legend': picture.legend, 'url': os.path.join('/', str(self.context['trek_pk']), settings.MEDIA_URL[1:], thdetail.name), }) return serialized class Meta: model = trekking_models.POI id_field = 'pk' geo_field = 'geometry' fields = ( 'id', 'pk', 'pictures', 'name', 'description', 'type', 'geometry', )
class PinSerializer(serializers.ModelSerializer): coords = geoserializers.GeometryField(label=('coordinates')) pinsize = serializers.SerializerMethodField('size') # def category_map(self, article): # return { # 'Science': 'science', # 'Health': 'health', # 'Job Market': 'economy', # 'World': 'world', # 'Workplace': 'conflict' # }.get(article.articlecategory, 'world') def size(self, article): # pprint(getattr(self.context['view'], 'max_retweetcount')) statcounts = getattr(self.context['view'], 'statcounts') # pprint(statcounts) pinsize = {} pinsize['twitter'] = 1.0 if statcounts['retweet']['max']==0 else 0.8*(article.retweetcount/statcounts['retweet']['max'])+0.2 #0.9*(article.retweetcount-statcounts['retweet']['min'])/statcounts['retweet']['maxmin']+0.1 pinsize['facebook'] = 1.0 if statcounts['share']['max']==0 else 0.8*(article.sharecount/statcounts['share']['max'])+0.2 #0.9*(article.sharecount-statcounts['share']['min'])/statcounts['share']['maxmin']+0.1 pinsize['both'] = 1.0 if statcounts['both']['max']==0 else 0.8*((article.retweetcount+article.sharecount)/statcounts['both']['max'])+0.2 #0.9*((article.retweetcount+article.sharecount)-statcounts['both']['min'])/statcounts['both']['maxmin']+0.1 # pprint(vars(self)) # pprint(vars(self.context['request'])) # pprint(vars(self.context['view'].request)) # print(self.context['request'] == self.context['view'].request) # pprint(getattr(self.context['view'], 'max_retweetcount')) # pprint(self.context['view'].filter_queryset(self.context['view'].queryset).aggregate(Max('retweetcount'))) # print('\nsize ') # print(self.context['request'].GET) # print(self.context['']) # print(Article.objects.filter(self.context['request'].GET)) return pinsize class Meta: model = Article fields = ('pk', 'date', 'coords', 'pinsize', 'headline', 'abstract', 'byline', 'url', 'category', 'retweetcount', 'sharecount') geo_field = 'coords'
class POISerializer(DynamicFieldsMixin, serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='apiv2:poi-detail') name = serializers.SerializerMethodField(read_only=True) description = serializers.SerializerMethodField(read_only=True) external_id = serializers.SerializerMethodField( read_only=True, help_text=_("External ID")) published = serializers.SerializerMethodField(read_only=True) create_datetime = serializers.SerializerMethodField(read_only=True) update_datetime = serializers.SerializerMethodField(read_only=True) geometry = geo_serializers.GeometryField(read_only=True, source="geom3d_transformed", precision=7) pictures = AttachmentSerializer(many=True, ) def get_published(self, obj): return get_translation_or_dict('published', self, obj) def get_external_id(self, obj): return obj.eid def get_name(self, obj): return get_translation_or_dict('name', self, obj) def get_update_datetime(self, obj): return obj.topo_object.date_update def get_create_datetime(self, obj): return obj.topo_object.date_insert def get_description(self, obj): return get_translation_or_dict('description', self, obj) class Meta: model = trekking_models.POI fields = ('id', 'create_datetime', 'description', 'external_id', 'geometry', 'name', 'pictures', 'published', 'type', 'update_datetime', 'url')