I’m moving the backend of a site to Django because it was originally coded in PHP and it’s the biggest mess on Earth or Mars… anyway.. so I copied the PHP and Python that I’ve conjured up to copy it below. They both return IDENTICAL values, but for some reason, the Django/Python doesn’t return anything from the query.
I’m up for suggestions, I’d consider installing GeoDjango, but I was hoping to get this going without having to do so.
So here’s the code:
PHP:
$lat = $myrow['latitude'];
$lon = $myrow['longitude'];
// get the min/max latitudes and longitudes for the radius search
$lat_range = $miles / 69.172;
$lon_range = abs($miles / (cos($lon) * 69.172));
$min_lat = $lat - $lat_range;
$max_lat = $lat + $lat_range;
$min_lon = $lon - $lon_range;
$max_lon = $lon + $lon_range;
$sql = "SELECT * FROM zipcodes WHERE
(latitude >= $min_lat AND latitude <= $max_lat AND
longitude >= $min_lon AND longitude <= $max_lon)";
Python:
distance = float(distance)
orderloc = Zipcodes.objects.get(zip=order.zip)
orderloc.longitude = float(orderloc.longitude)
orderloc.latitude = float(orderloc.latitude)
latrange = distance/69.172
lonrange = math.fabs(distance/(math.cos(orderloc.longitude) * 69.172))
minlat = orderloc.latitude - latrange
maxlat = orderloc.latitude + latrange
minlon = orderloc.longitude - lonrange
maxlon = orderloc.longitude + lonrange
distanceresults = Zipcodes.objects.all().filter(longitude__gte=minlon,
longitude__lte=maxlon,latitude__gte=minlat,latitude__lte=maxlat)
P.S. This is the query that Django returns…
SELECT (a ton of stuff here) FROM `zipcodes` WHERE (`zipcodes`.`longitude` <= -74.489601513 AND `zipcodes`.`longitude` >= -75.957598487 AND `zipcodes`.`latitude` >= 39.8528641705 AND `zipcodes`.`latitude` <= 41.2985358295 )
I noticed that you’re converting the latitude and longitude on
orderlocto floats. What field type are they on your model in the first place? Django has aFloatFieldfield type, so if you’re dealing with floats, you should use that field type on your model. I’m thinking based on this that it might be an issue of comparing the actual true-blue float with something like a CHAR value, and it’s not exactly matching.Alternatively, floats in Python can be a little weird sometimes, returning numbers like 25.00000000001 instead of an even 25 after doing calculations. Since you’re dealing with latitude and longitude, which typically have a fixed set of digits, you might also try using
DecimalFields. These essentially function like floats, but limit stored data to a defined number of places. Again, just throwing out ideas.