Django: Filter on Annotated ValueHow do I do a not equal in Django queryset filtering?Does Django scale?How to get places with a certain radiusdifferentiate null=True, blank=True in djangoMySQL - Ordered GROUP BY Issue OptimizationPHP MySQL statement - “select as” with “where”Aggregate (and other annotated) fields in Django Rest Framework serializersadd raw sql where clause to django querysetAggregation of an annotation in GROUP BY in DjangoAdd my own query parameters to django admin
What is the name of this type of figure?
Delete the following space
Conflict between senior and junior members
Can machine learning learn a function like finding maximum from a list?
Disease transmitted by postage stamps
Password management for kids - what's a good way to start?
Just how much information should you share with a former client?
Can birds evolve without trees?
What is the relation between Shang-Chi and the Mandarin in the comics?
Derivative is just speed of change?
Is Norway in the Single Market?
Russian pronunciation of /etc (a directory)
Should 2FA be enabled on service accounts?
Are some indefinite integrals impossible to compute or just don't exist?
Why don't short runways use ramps for takeoff?
Can the additional attack from a Samurai's Rapid Strike have advantage?
How can a class have multiple methods without breaking the single responsibility principle
Why did the United States not resort to nuclear weapons in Vietnam?
Should students have access to past exams or an exam bank?
Is this popular optical illusion made of a grey-scale image with coloured lines?
Skipping same old introductions
A conjectural trigonometric identity
Why are prop blades not shaped like household fan blades?
How to prevent a single-element caster from being useless against immune foes?
Django: Filter on Annotated Value
How do I do a not equal in Django queryset filtering?Does Django scale?How to get places with a certain radiusdifferentiate null=True, blank=True in djangoMySQL - Ordered GROUP BY Issue OptimizationPHP MySQL statement - “select as” with “where”Aggregate (and other annotated) fields in Django Rest Framework serializersadd raw sql where clause to django querysetAggregation of an annotation in GROUP BY in DjangoAdd my own query parameters to django admin
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a situation where I have a model called trip
. Each trip has a departure_airport
and an arrival_airport
which are related fields and both part of the airport
model. Each object in the airport model has a location represented by latitude
and longitude
fields.
I need to be able to take inputs from two (potentially) separate departure and arrival airport locations using something like the Haversine formula. That formula would calculate the distance from each departure/arrival airport in the database to the location of the airports that have been taken as input.
The difficult part of this query is that I annotate the trip queryset with the locations of the departure and arrival airports, however because there's two sets of latitude/longitude fields (one for each airport) with the same name and you can't use annotated fields in a sql where clause, I'm not able to use both sets of airports in a query.
I believe the solution is to use a subquery on the annotated fields so that query executes before the where clause, however I've been unable to determine if this is possible for this query. The other option is to write raw_sql.
Here's what I have so far:
GCD_FORMULA_TO = """3961 * acos(
cos(radians(%s)) * cos(radians(arrival_lat))
* cos(radians(arrival_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(arrival_lat)))"""
GCD_FORMULA_FROM = """3961 * acos(
cos(radians(%s)) * cos(radians(departure_lat))
* cos(radians(departure_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(departure_lat)))"""
location_to = Q(location_to__lt=self.arrival_airport_rad)
location_from = Q(location_from__lt=self.departure_airport_rad)
qs = self.queryset
.annotate(arrival_lat=F('arrival_airport__latitude_deg'))
.annotate(arrival_lon_to=F('arrival_airport__longitude_deg'))
.annotate(departure_lat=F('departure_airport__latitude_deg'))
.annotate(longitude_lon=F('departure_airport__longitude_deg'))
.annotate(location_to=RawSQL(GCD_FORMULA_TO, (self.arrival_airport.latitude_deg, self.arrival_airport.longitude_deg,
self.arrival_airport.latitude_deg)))
.annotate(location_from=RawSQL(self.GCD_FORMULA_FROM, (self.departure_airport.latitude_deg, self.departure_airport.longitude_deg,
self.departure_airport.latitude_deg)))
.filter(location_to and location_from)
return qs
Any ideas? Also open to other ways to go about this.
mysql django python-3.x
add a comment |
I have a situation where I have a model called trip
. Each trip has a departure_airport
and an arrival_airport
which are related fields and both part of the airport
model. Each object in the airport model has a location represented by latitude
and longitude
fields.
I need to be able to take inputs from two (potentially) separate departure and arrival airport locations using something like the Haversine formula. That formula would calculate the distance from each departure/arrival airport in the database to the location of the airports that have been taken as input.
The difficult part of this query is that I annotate the trip queryset with the locations of the departure and arrival airports, however because there's two sets of latitude/longitude fields (one for each airport) with the same name and you can't use annotated fields in a sql where clause, I'm not able to use both sets of airports in a query.
I believe the solution is to use a subquery on the annotated fields so that query executes before the where clause, however I've been unable to determine if this is possible for this query. The other option is to write raw_sql.
Here's what I have so far:
GCD_FORMULA_TO = """3961 * acos(
cos(radians(%s)) * cos(radians(arrival_lat))
* cos(radians(arrival_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(arrival_lat)))"""
GCD_FORMULA_FROM = """3961 * acos(
cos(radians(%s)) * cos(radians(departure_lat))
* cos(radians(departure_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(departure_lat)))"""
location_to = Q(location_to__lt=self.arrival_airport_rad)
location_from = Q(location_from__lt=self.departure_airport_rad)
qs = self.queryset
.annotate(arrival_lat=F('arrival_airport__latitude_deg'))
.annotate(arrival_lon_to=F('arrival_airport__longitude_deg'))
.annotate(departure_lat=F('departure_airport__latitude_deg'))
.annotate(longitude_lon=F('departure_airport__longitude_deg'))
.annotate(location_to=RawSQL(GCD_FORMULA_TO, (self.arrival_airport.latitude_deg, self.arrival_airport.longitude_deg,
self.arrival_airport.latitude_deg)))
.annotate(location_from=RawSQL(self.GCD_FORMULA_FROM, (self.departure_airport.latitude_deg, self.departure_airport.longitude_deg,
self.departure_airport.latitude_deg)))
.filter(location_to and location_from)
return qs
Any ideas? Also open to other ways to go about this.
mysql django python-3.x
add a comment |
I have a situation where I have a model called trip
. Each trip has a departure_airport
and an arrival_airport
which are related fields and both part of the airport
model. Each object in the airport model has a location represented by latitude
and longitude
fields.
I need to be able to take inputs from two (potentially) separate departure and arrival airport locations using something like the Haversine formula. That formula would calculate the distance from each departure/arrival airport in the database to the location of the airports that have been taken as input.
The difficult part of this query is that I annotate the trip queryset with the locations of the departure and arrival airports, however because there's two sets of latitude/longitude fields (one for each airport) with the same name and you can't use annotated fields in a sql where clause, I'm not able to use both sets of airports in a query.
I believe the solution is to use a subquery on the annotated fields so that query executes before the where clause, however I've been unable to determine if this is possible for this query. The other option is to write raw_sql.
Here's what I have so far:
GCD_FORMULA_TO = """3961 * acos(
cos(radians(%s)) * cos(radians(arrival_lat))
* cos(radians(arrival_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(arrival_lat)))"""
GCD_FORMULA_FROM = """3961 * acos(
cos(radians(%s)) * cos(radians(departure_lat))
* cos(radians(departure_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(departure_lat)))"""
location_to = Q(location_to__lt=self.arrival_airport_rad)
location_from = Q(location_from__lt=self.departure_airport_rad)
qs = self.queryset
.annotate(arrival_lat=F('arrival_airport__latitude_deg'))
.annotate(arrival_lon_to=F('arrival_airport__longitude_deg'))
.annotate(departure_lat=F('departure_airport__latitude_deg'))
.annotate(longitude_lon=F('departure_airport__longitude_deg'))
.annotate(location_to=RawSQL(GCD_FORMULA_TO, (self.arrival_airport.latitude_deg, self.arrival_airport.longitude_deg,
self.arrival_airport.latitude_deg)))
.annotate(location_from=RawSQL(self.GCD_FORMULA_FROM, (self.departure_airport.latitude_deg, self.departure_airport.longitude_deg,
self.departure_airport.latitude_deg)))
.filter(location_to and location_from)
return qs
Any ideas? Also open to other ways to go about this.
mysql django python-3.x
I have a situation where I have a model called trip
. Each trip has a departure_airport
and an arrival_airport
which are related fields and both part of the airport
model. Each object in the airport model has a location represented by latitude
and longitude
fields.
I need to be able to take inputs from two (potentially) separate departure and arrival airport locations using something like the Haversine formula. That formula would calculate the distance from each departure/arrival airport in the database to the location of the airports that have been taken as input.
The difficult part of this query is that I annotate the trip queryset with the locations of the departure and arrival airports, however because there's two sets of latitude/longitude fields (one for each airport) with the same name and you can't use annotated fields in a sql where clause, I'm not able to use both sets of airports in a query.
I believe the solution is to use a subquery on the annotated fields so that query executes before the where clause, however I've been unable to determine if this is possible for this query. The other option is to write raw_sql.
Here's what I have so far:
GCD_FORMULA_TO = """3961 * acos(
cos(radians(%s)) * cos(radians(arrival_lat))
* cos(radians(arrival_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(arrival_lat)))"""
GCD_FORMULA_FROM = """3961 * acos(
cos(radians(%s)) * cos(radians(departure_lat))
* cos(radians(departure_lon) - radians(%s)) +
sin(radians(%s)) * sin(radians(departure_lat)))"""
location_to = Q(location_to__lt=self.arrival_airport_rad)
location_from = Q(location_from__lt=self.departure_airport_rad)
qs = self.queryset
.annotate(arrival_lat=F('arrival_airport__latitude_deg'))
.annotate(arrival_lon_to=F('arrival_airport__longitude_deg'))
.annotate(departure_lat=F('departure_airport__latitude_deg'))
.annotate(longitude_lon=F('departure_airport__longitude_deg'))
.annotate(location_to=RawSQL(GCD_FORMULA_TO, (self.arrival_airport.latitude_deg, self.arrival_airport.longitude_deg,
self.arrival_airport.latitude_deg)))
.annotate(location_from=RawSQL(self.GCD_FORMULA_FROM, (self.departure_airport.latitude_deg, self.departure_airport.longitude_deg,
self.departure_airport.latitude_deg)))
.filter(location_to and location_from)
return qs
Any ideas? Also open to other ways to go about this.
mysql django python-3.x
mysql django python-3.x
asked Mar 26 at 22:58
Braden HoltBraden Holt
6831 gold badge7 silver badges18 bronze badges
6831 gold badge7 silver badges18 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You're doing this the hard way.
If your python code has a pair of locations, use this:
from geopy.distance import distance
loc1 = (lat1, lng1)
loc2 = (lat2, lng2)
d = distance(loc1, loc2).km
If you're querying a database, perhaps you would prefer that it runs PostGIS / Postgres, rather than mysql,
so you can compute distance and shape membership.
The syntax sometimes is on the clunky side, but the indexing works great.
Here is an example for departing from London Heathrow:
SELECT a.airport_name,
ST_Distance('SRID=4326; POINT(-0.461389 51.4775)'::geography,
ST_Point(a.longitude, a.latitude)) AS distance
FROM arrival_airports a
ORDER BY distance;
As a separate matter, you might consider defining an arrival and/or departure VIEW on your table, and then JOIN, with a distinct model for each view.
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367376%2fdjango-filter-on-annotated-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You're doing this the hard way.
If your python code has a pair of locations, use this:
from geopy.distance import distance
loc1 = (lat1, lng1)
loc2 = (lat2, lng2)
d = distance(loc1, loc2).km
If you're querying a database, perhaps you would prefer that it runs PostGIS / Postgres, rather than mysql,
so you can compute distance and shape membership.
The syntax sometimes is on the clunky side, but the indexing works great.
Here is an example for departing from London Heathrow:
SELECT a.airport_name,
ST_Distance('SRID=4326; POINT(-0.461389 51.4775)'::geography,
ST_Point(a.longitude, a.latitude)) AS distance
FROM arrival_airports a
ORDER BY distance;
As a separate matter, you might consider defining an arrival and/or departure VIEW on your table, and then JOIN, with a distinct model for each view.
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
add a comment |
You're doing this the hard way.
If your python code has a pair of locations, use this:
from geopy.distance import distance
loc1 = (lat1, lng1)
loc2 = (lat2, lng2)
d = distance(loc1, loc2).km
If you're querying a database, perhaps you would prefer that it runs PostGIS / Postgres, rather than mysql,
so you can compute distance and shape membership.
The syntax sometimes is on the clunky side, but the indexing works great.
Here is an example for departing from London Heathrow:
SELECT a.airport_name,
ST_Distance('SRID=4326; POINT(-0.461389 51.4775)'::geography,
ST_Point(a.longitude, a.latitude)) AS distance
FROM arrival_airports a
ORDER BY distance;
As a separate matter, you might consider defining an arrival and/or departure VIEW on your table, and then JOIN, with a distinct model for each view.
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
add a comment |
You're doing this the hard way.
If your python code has a pair of locations, use this:
from geopy.distance import distance
loc1 = (lat1, lng1)
loc2 = (lat2, lng2)
d = distance(loc1, loc2).km
If you're querying a database, perhaps you would prefer that it runs PostGIS / Postgres, rather than mysql,
so you can compute distance and shape membership.
The syntax sometimes is on the clunky side, but the indexing works great.
Here is an example for departing from London Heathrow:
SELECT a.airport_name,
ST_Distance('SRID=4326; POINT(-0.461389 51.4775)'::geography,
ST_Point(a.longitude, a.latitude)) AS distance
FROM arrival_airports a
ORDER BY distance;
As a separate matter, you might consider defining an arrival and/or departure VIEW on your table, and then JOIN, with a distinct model for each view.
You're doing this the hard way.
If your python code has a pair of locations, use this:
from geopy.distance import distance
loc1 = (lat1, lng1)
loc2 = (lat2, lng2)
d = distance(loc1, loc2).km
If you're querying a database, perhaps you would prefer that it runs PostGIS / Postgres, rather than mysql,
so you can compute distance and shape membership.
The syntax sometimes is on the clunky side, but the indexing works great.
Here is an example for departing from London Heathrow:
SELECT a.airport_name,
ST_Distance('SRID=4326; POINT(-0.461389 51.4775)'::geography,
ST_Point(a.longitude, a.latitude)) AS distance
FROM arrival_airports a
ORDER BY distance;
As a separate matter, you might consider defining an arrival and/or departure VIEW on your table, and then JOIN, with a distinct model for each view.
edited Mar 27 at 17:19
answered Mar 27 at 0:18
J_HJ_H
6,0891 gold badge9 silver badges24 bronze badges
6,0891 gold badge9 silver badges24 bronze badges
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
add a comment |
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
In a perfect world I'd figure out the sql query but don't have the time now. This works great. Thanks!
– Braden Holt
Mar 27 at 17:08
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367376%2fdjango-filter-on-annotated-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown