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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현