How to create a gdal.Dataset or xarray.Dataset object from a django.contrib.gis.gdal.GDALRaster object?

Viewed 500

I am working on a Django project in which I'm trying to get all the raster data from my Database.

Here is my model in models.py

from django.contrib.gis.db import models
class RasterWithName(models.Model):
    raster = models.RasterField()
    name = models.TextField()

Here is the method I use to get all the rows from my Database in django's shell.

First I have to do a python manage.py shell and then run the below code, one by one:

all_objects = RasterWithName.objects.all()
first_object_in_database = all_objects[0]
print(first_object_in_database)

It prints:

RasterWithName object (1)

Additionally, running the below line,

print(type(first_object_in_database))

prints:

<class 'geo.models.RasterWithName'>

I then run the two lines below:

raster = first_object_in_database.raster
print(type(raster))

Which prints:

<class 'django.contrib.gis.gdal.raster.source.GDALRaster'>

How can I convert this GDALRaster object into a more known object like a gdal Dataset( that can be imported like this: from osgeo.gdal import Dataset) or xarray Dataset (that can be imported like this: from xarray import Dataset)?

#####################################################

EDIT‌ #1:

#####################################################

Thanks to Val, Here is a working solution:

all_objects = RasterWithName.objects.all()
first_object_in_database = all_objects[0]

my_raster = first_object_in_database.raster

gdal_raster = gdal.Open(raster.name)

print(type(gdal_raster))

which prints:

<class 'osgeo.gdal.Dataset'>

However, I don't think this would be very optimal since it simply opens the file from its path on my local storage.

0 Answers
Related