3

I am newbie to Django and developing a REST API using Django Rest Framework (DRF) and GIS. Previously, I was using an SQL query for transforming a geometry:

select
    id, 
    name, 
    round(value::numeric, 2) as value,
    st_transform(geometry, 3857) as geometry
from
    my_model

...

class MyModel(models.Model):
    name = models.CharField(max_length=50, blank=True)
    value = models.FloatField()
    geometry = models.GeometryField(null=True, blank=True)


    class Meta:
        db_table = u'my_model'

    def __unicode__(self):
        return '%s' % self.name

Here serializer class:

class MyModelSerializer(serializers.GeoModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'name', 'value', 'geometry')

I have also tried to do this way but cannot transform output

class MyModelViewSet(viewsets.ModelViewSet):

    queryset = MyModel.objects.all().transform(3857)
    serializer_class = MyModelSerializer

How can I do this in Django Rest Framework and GIS? Where can I get query sample or a comprehensive tutorial for DRF?

nemesisdesign
  • 8,159
  • 12
  • 58
  • 97
Shoaib Ijaz
  • 5,347
  • 12
  • 56
  • 84

2 Answers2

3

Solved:

Add the srid argument to transform function. I was considering as

transform(srid)

first argument as srid but should be like this

transform(srid=3857)

class MyModelViewSet(viewsets.ModelViewSet):

    queryset = MyModel.objects.all().transform(srid=3857)
    serializer_class = MyModelSerializer
Shoaib Ijaz
  • 5,347
  • 12
  • 56
  • 84
  • This gives me: `AttributeError: 'QuerySet' object has no attribute 'transform'` where does function `transform()` comes from? do you have related docs? – Henhuy Nov 17 '20 at 13:34
  • Maybe, this can help you https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry.transform – Shoaib Ijaz Nov 18 '20 at 12:24
  • https://gis.stackexchange.com/questions/94640/geodjango-transform-not-working – Shoaib Ijaz Nov 18 '20 at 12:24
  • But as I understand (from here: https://stackoverflow.com/a/48840336/5804947) the `transform()` function has been deprecated and replaced by database function [`Transform`](https://docs.djangoproject.com/en/3.1/ref/contrib/gis/functions/#django.contrib.gis.db.models.functions.Transform), correct? But then I cannot use answer given above as annotations dont work with `GeoModelSerializer` (see my issue https://github.com/openwisp/django-rest-framework-gis/issues/250) – Henhuy Nov 18 '20 at 12:48
2

You can provide a default SRID to your GeometryField -

geometry = models.GeometryField(srid=3857, null=True, blank=True)

And Django will automatically handle the conversion. More details on the doc and tutorial.

Where can i get queries sample or comprehensive tutorial for rest framework gis?

You can find all about geodjango on Django documentation. Django rest framework is noting but Django.

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96