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;








1















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.










share|improve this question






























    1















    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.










    share|improve this question


























      1












      1








      1








      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.










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 22:58









      Braden HoltBraden Holt

      6831 gold badge7 silver badges18 bronze badges




      6831 gold badge7 silver badges18 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          1














          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.






          share|improve this answer



























          • 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










          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
          );



          );













          draft saved

          draft discarded


















          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









          1














          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.






          share|improve this answer



























          • 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















          1














          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.






          share|improve this answer



























          • 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













          1












          1








          1







          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          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

















          • 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








          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.



















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript