简体   繁体   中英

How to access a point in postgis database from Django?

I am trying to get points (latitude longitude coordinates) from my database using django / postgis, but I run into this error that I can't figure:

django.db.utils.ProgrammingError: cannot cast type point to bytea
LINE 1: ...lon_id", "lat_lon"."house_id", "lat_lon"."lat_lon"::bytea FR...

My database looks like this:

经纬度数据库

And I set up my model (models.py) like this:

class LatLon(models.Model):
    lat_lon_id = models.AutoField(primary_key=True)
    house = models.ForeignKey(Houses, models.DO_NOTHING)
    lat_lon = models.PointField()

    class Meta:
        managed = False
        db_table = 'lat_lon'
    
    @property
    def lat_lng(self):
        return(list(getattr(self.lat_lon, 'coords', []))[::-1])

and make a listview (views.py):

class LatlonList(ListView):
    queryset = LatLon.objects.filter(lat_lon__isnull=False)

Finally my urlpatterns look like this:

urlpatterns = [
    path("", views.home, name="home"),
    path("hello/<name>", views.hello_there, name="hello_there"),
    path("about/", views.about, name="about"),
    path("contact/", views.contact, name="contact"),
    path("log/", views.log_message, name="log"),
    path("test_page/", views.LatlonList.as_view(template_name = 'test_page.html'), name="test_page"),
    path('map/', views.EntryList.as_view()),

I guess from the error that Django tries to cast my points to bytea data type, but I clearly specify in the model that they are points (Pointfield).

I am new to django, so any responses/hints are appreciated!

I figured out the solution thanks to geozlot's comment.

I choose to add a geometry column to the database with the sql statement:

SELECT AddGeometryColumn('lat_lon', 'lat_lon', 4326, 'POINT', 2, true)

Next, I can write PostGIS' geometry points to this column using;

ST_SetSRID(ST_MakePoint(%s, %s), 4326))

where %s are placeholders for the longtitude and latitude.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM