Search code examples
pythondjangogeometrygeodjangocentroid

Geodjango Querying geometry returns pointer instead of geometry


I am trying to get a single MultiPolygon geometry in a Queryset from this model:

class local_administrative_unit(models.Model):
    lau_id = models.IntegerField(primary_key=True)
    lau_name = models.CharField(max_length=150)
    adm_level_2 = models.ForeignKey('administrative_level_2', on_delete=models.PROTECT)
    geom = models.MultiPolygonField(srid=4326)

trying it this way in the Django shell:

local_administrative_unit.objects.get(lau_id=1).geom

which returned:

<MultiPolygon object at 0x7fb12af0ab10>

when I pass this to the Centroid function, it does not what I was looking for:

Centroid(Value(<MultiPolygon object at 0x7fb12af0ac90>))

Can you please tell me how I get the actual geometry to use it afterwards - for example for calculating the Centroid of that polygon? Looks like I am getting a pointer to what I am looking for instead of the actual thing.

Thanks in advance.


Solution

  • Meanwhile I found what i missed. It is basically all explained in the GeoDjango Tutorial which i appearently overlooked before. GeoDjango creates a GEOSGeometry object when the geometry is first accessed on which certain properties then can be used to do stuff. In the above case this means:

    foo = local_administrative_unit.objects.get(lau_id=1).geom
    print(foo)
    <MultiPolygon object at 0x7fb12af0ab10>
    

    foo holds the geometry object as the one in the initial example, to get the centroid in a generally useable form we can just use some properties:

    bar = foo.centroid
    bar.wkt
    

    This will calculate the centroid and return it then in well-known text.