Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter geodjango based on longitude and latitude

I have an application that has been storing longitude and latitude now i want to integrate it with geodjango the application looks like this.

class Location(models.Model):
    #other fields here
    lat = models.CharField(blank=True, max_length=100)
    lng = models.CharField(blank=True, max_length=100)

now I will like to filter locations based on a distance say filter all location 1km away from location with pk = 1 using django.contrib.gis.measure import D and GEOSGeometry or should i refactor the model to have point rather than longitude and latitude so i can do something like this :

Location.objects.filter(point__dwithin=(D(km=5)))

any advice and recommendations will do.

like image 810
user1940979 Avatar asked Oct 16 '25 20:10

user1940979


1 Answers

Schema Migration

Fast forward 2016, and we have migrations built into django you no longer need south. You need only two migrations instead of three.

Step 1: change the model.

class Location(models.Model):
    #other fields here
    lat = models.CharField(blank=True, max_length=100)
    lng = models.CharField(blank=True, max_length=100)

    point = models.PointField(null=True)

step 2: create the migration

./manage.py makemigrations

Data Migration

This is the third step and involves editing the migration file created above, look at the operations section and add

migrations.RunSQL('''UPDATE myapp_location SET `point` = Point(lat,lng)''')

This query is for mysql. If you are using PostGis your query would be

migrations.RunSQL('''UPDATE myapp_location SET "point" = ST_MakePoint(lng,lat)''')

Note that the format for postgis is lng,lat Note that this is a single query and should execute reasonably quickly. To iterate through all the rows with python and update them one by one would mean a million queries if you have a million records!

Step 4: ./manage.py migrate

Step 5: drop the lat, lng columns from the model.

step 6: ./manage.py makemigrations

step 7: ./manage.py migrate

like image 188
e4c5 Avatar answered Oct 18 '25 16:10

e4c5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!