Remix.run Logo
ErroneousBosh a day ago

> The one thing I really appreciate with the ORM is that you really can get the ORM to make... more or less any sort of SQL query you want.

And if you can't make the ORM make the SQL query you want, you can just write it as a SQL query, like this godawful monstrosity:

      x = Site.objects.raw("select id, name, lat, lon, 111.045*degrees(acos(cos( \
        radians(latpoint))*cos(radians(lat)) \
        *cos(radians(lngpoint)-radians(lon)) \
        +sin(radians(latpoint))*sin(radians(lat)))) \
        as distance from sites_site join \
        (select %s as latpoint, %s as lngpoint) as p on 1=1 \
        order by distance limit 5", [float(lat), float(lon)])
... which calculates the Haversine distance from where you are now to the five nearest points.

I am in roughly equal parts proud of and horrified by this creation.

rtpg a day ago | parent | next [-]

Site.objects.annotate( distance=Degrees(ACos(Cos(.....))), latpoint=float(lat), lngpoint=float(lon), ).order_by("distance")[:5]

for function calls, look at django.db.models.functions, you can find a bunch of stuff in there or create custom ones super easily (like "two lines of codes" easily)

I mean you have a thing that works in theory so it's a bit of navel gazing, though.

ErroneousBosh an hour ago | parent [-]

That is actually awesome :-) I'll try that.

I was really just going to try and wrap it in a function to stick in the model so I can say something like Site.objects.get(id=thing).distance_from(lat,long) in.

But, now the bit that I was calling that from is actually being done from a websocket handler, and that's written in Go because Django and websockets seems very complex.

ranger_danger a day ago | parent | prev [-]

I'm not seeing anything that can't be done here without using raw() though?

ErroneousBosh a day ago | parent [-]

Yeah I'm not clever enough to do that.

How would you have approached it?