2 ms·
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. It can take a while t
by rtpg 2mo 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.
It can take a while to wrap your head around what fields get used in aggregates and the like, but when working with big models with like 65 fields and juggling a bunch of stuff, not having to futz with serialization/deserialization and "just" expressing your problem in the dumb way is nice.
I want to say this all comes back to bite you in the end but honestly it's more just having wide tables that comes to bite you. A service layer wouldn't really save you. Meanwhile you save yourself a bunch of tedium in the mean time
- ErroneousBosh 2mo 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.
- ranger_danger 2mo agoI'm not seeing anything that can't be done here without using raw() though?
- ErroneousBosh 2mo agoYeah I'm not clever enough to do that. How would you have approached it?
- ranger_danger 2mo agoIt looks like GeoJSON implements some distance lookups that make this more django-y, that's probably the easiest way. But I doubt they're using raw() either.
- rtpg 2mo agoSite.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 2mo agoThat 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.