What I love about Django
Posted by j4mie 23 hours ago
Comments
Comment by matsemann 22 hours ago
* Models being passed around everywhere, queries happening everywhere. I prefer having a dedicated service/selector layer to do those things. Then convert to pydantic objects or something that's passed around further.
* Corollary, but adding stuff to querymanagers quickly goes out of control. Sure, it's nice to reuse MyModel.objects.annotate_something().annotate_something_else().... but it can quickly become unwieldy and even wrong with exploding joins. And it promotes doing queries in places they shouldn't happen.
* It's veeery easy to make spaghetti. Very easy to query across boundaries, into other apps. Fine on smaller projects, but in huge codebases it quickly makes things hard to control, especially since it's all stringly typed. If I want to modify my model, it's hard to know if someone else have done a query where they did theirmodel__some_relation__another_relation__mymodel__some_field. Blows up in production.
* For some reason it's very common in Django/python projects to have types.py, models.py, selectors.py, views.py, services.py etc. And then each of those end up with lots of unrelated things in the same python file, while related stuff is spread over many files. Django apps doesn't really solve this cleanly either.
Comment by adsharma 8 hours ago
https://adsharma.github.io/django-fquery/
Your models can be plain old python data classes, declaratively mapped to Django primitives.
Comment by Oxodao 21 hours ago
Comment by zelphirkalt 21 hours ago
Comment by Oxodao 19 hours ago
[1] https://www.doctrine-project.org/projects/doctrine-collectio... (for collections but you can use them for queries too)
[2] https://www.doctrine-project.org/projects/doctrine-orm/en/3.... / https://www.doctrine-project.org/projects/doctrine-orm/en/3....
Comment by ErroneousBosh 19 hours ago
And, rather like the petrol engine, it turns out while it sucks, everything else is massively worse in some vitally important way.
Comment by JodieBenitez 21 hours ago
Comment by Oxodao 19 hours ago
Comment by DarkNova6 21 hours ago
Never in my life did I have a problem with lazy loading causing unbearable performance until I joined a Python Django team. I really tried to find sympathy for the "dynamically typed" folks (please spare me saying Python is technically statically typed), but coming from writing apps and backends in Java, Swift, C#, Objective-C and PHP, Python with Django was the worst experience bar none.
I worked on the project for 10 months, could at least refactor the project to something semi-sane where obvious mistakes (which would not be possible in other languages) could not happen. Then along comes a "good Python dev" and threw it all out of the window and start doing SQL queries all over the place (typically 3-6 lines long), remove the domain objects and cause the same problems I started with to begin with. But his approach was saying that the other developers were "not good enough".
Yeah, have fun with schema changes going forward. Good riddance.
Comment by senko 21 hours ago
I've seen the horrors Java devs start doing on a Python project when trying to "fix" things, where by "fix" they mean use patterns they had to in previous gigs.
It's a different world.
Comment by DarkNova6 21 hours ago
Comment by senko 20 hours ago
In Django you'd typically use simple classes (models or forms, or even dataclasses nowadays) more than dicts everywhere; n+1 is trivially avoidable (as another sibling comment points out, and you also have multiple packages that autodetect such cases if you've missed them).
Python in general has a more "consenting adults" than "defensive programming" attitude (which doesn't mean exessive coupling or spaghetti, but the approach is different from the Java or C# mindset).
There's no one THE correct style of programming.
Comment by matsemann 1 hour ago
No, it doesn't. It's fair to criticize the consequences of this approach to coding.
Comment by JodieBenitez 21 hours ago
select_related, prefetch_related. n+1 problems be gone.
Comment by DarkNova6 21 hours ago
We did do that and that's why our queries ended up being several lines long. But if you missed just one model? You openly walk a knife again.
It's a mess and it only gets longer and longer. I ended the project with having some proper aggregates, only for that to be thrown out of the window by the guy after me.
Comment by infamia 12 hours ago
https://docs.djangoproject.com/en/dev/releases/6.1/#model-fi...
That's the great thing about Django, it's been around so long and the quality bar is so high that eventually all the major rough edges get sanded away usually in a really well considered manner.
Comment by JodieBenitez 19 hours ago
Which is... perfectly normal for non-trivial needs.
> I ended the project with having some proper aggregates, only for that to be thrown out of the window by the guy after me.
How is that a Django problem though ? Sounds like a skill issue on your successor.
I get what you say, there's plenty of debates about ActiveRecord vs. AnythingElse, but in the end this one has its use and obviously has served many of us just fine. Different strokes... you know the drill.
Comment by lozenge 14 hours ago
Comment by JodieBenitez 3 hours ago
Comment by ranger_danger 16 hours ago
Then it got to where I had to make a reflective function that I use like Model.objects.defer(*all_fields_except(Model, ['field1', 'field2'])), and then add another all_fields_except() for every select_related and prefetch_related.
Even save() by default re-writes every single field. You have to use save(update_fields=['field1']) instead.
Comment by ErroneousBosh 19 hours ago
Comment by kitsune_ 21 hours ago
Comment by rtpg 19 hours ago
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
Comment by ErroneousBosh 19 hours ago
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.
Comment by rtpg 7 hours ago
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.
Comment by ranger_danger 16 hours ago
Comment by ErroneousBosh 13 hours ago
How would you have approached it?
Comment by braiamp 20 hours ago
Comment by nesarkvechnep 20 hours ago
Comment by physicsguy 20 hours ago
Comment by pmontra 19 hours ago
Comment by FranOntanaya 19 hours ago
Kinda took until Facebook showing off Hacklang in 2014 for people to believe in getting more canonical programming features into PHP and make it more performant. So it would have been a good decision if one could predict 10 years into the future, but nobody can.
Comment by dofm 18 hours ago
Comment by thunky 18 hours ago
Comment by worldthruword 16 hours ago
Comment by ErroneousBosh 19 hours ago
Comment by sgt 19 hours ago
> Models being passed around everywhere, queries happening everywhere.
No, as a developer you still need to be 100% aware of the underlying queries and potential performance issues. No excuse for N+1 problems. ORM is not an excuse to be lazy, but I admit it will probably catch quite a few developers.
Those same developers would probably make a mess out of any other framework or technology though.
Comment by strogonoff 18 hours ago
It definitely takes a bit of discipline. The key layers are somewhat easy to manage—middleware, context processors, views, template tags—but I’ve seen some hairy lasagne further obscuring where the queries happen on top of that. A well-documented abstraction can be useful, but if it is possible to keep it simple and obvious then that’s the way to go.
(Third-party dependencies can further complicate things, but at least you can expect a library using ORM to be in the installed apps list.)
Comment by sgt 14 hours ago
It's highly productive if you do it right.
Comment by JodieBenitez 22 hours ago
Comment by almost 20 hours ago
Comment by JodieBenitez 17 hours ago
Comment by dzonga 19 hours ago
that means you can mold it to fit your use case easily - don't like the ORM - you can plug SQLalchemy and use a different 'architecture'. + you can use multiple different databases if you think that's the right path. in Django there's no 'the rails way' - you choose your own path.
Django-admin by itself saves so much work specially If you're doing B2B stuff & you gotta onboard users.
I guess Django is not the best thing, but not the worst thing either. so a perfect middle ground.
Comment by gls2ro 13 hours ago
The Rails Way is a response to people changing too much Rails and making it super custom.
In the last 4 years alone I touched codebases ranging from Rails Way to Rails and everything dry.rb, to Rails and Grape and Sorbet, to Rails and service objects everywhere and a lot more combinations.
Comment by dzonga 16 hours ago
whereas Django though it also provides almost similar abstractions in terms of CRUD - it doesn't assume your app will only do CRUD stuff - hence the flexibility e.g there's many apps where you only have a handful of endpoints that are user accessible maybe at most 15, then of course management of users via Django-admin but everything else is non CRUD e.g calling other systems
[0]: https://jeromedalbert.com/how-dhh-organizes-his-rails-contro...
Comment by saaspirant 21 hours ago
This article is very useful.
I use DRF but not serializers and write validations by hand because it is too abstract for me.
My views just call services and return the result.
Comment by giancarlostoro 19 hours ago
Comment by stuaxo 22 hours ago
I've been meaning to do my own Django post, on some other bits we take for granted - I should do it.
People should be using Django, the best parts are so useful you don't notice them until you switch platforms and implement them badly.
Every app that used a more narrow solution ultimately ends up implementing parts of Django badly.
The best way to solve this from Djangos side would be to have official ways of:
- Using the ORM outside of Django - Doing single file Django apps
Both of these have various 3rd party solutions, which shows demand.
In the past other bits of Django have been split off by 3rd parties but those two are the places to start.
Comment by cudder 14 hours ago
Comment by ErroneousBosh 19 hours ago
Comment by Klonoar 22 hours ago
Django is hands down one of my favorite frameworks ever created, and the only one I still reach for in some contexts. For a lot of projects I use it to drive database migrations, and stand up an easy admin portal for others to use - then anything else is driven by an API layer written in (e.g) Rust.
I haven't had to care about Django's performance in years but still get to reap some of the benefits.
Comment by zelphirkalt 20 hours ago
Comment by Klonoar 19 hours ago
Just read from the database and treat Django as a DB builder/migrator/inspector.
Comment by tclancy 19 hours ago
Comment by 0x4d4c 22 hours ago
But I also remember, that some non-standard requirements were really difficult to implement or get around.
Having that in mind, the next project was entirely in Pylons. All was good, until we were asked to add Unicode support.
Since them I'm on Rails.
Comment by thraxil 21 hours ago
How long ago was this? I feel like unicode has kind of been a solved problem in Python since python3 came out. In the python2 days it was, indeed, miserable.
Comment by whateverboat 21 hours ago
DjangoCon 2008 Keynote: Cal Henderson
Comment by tonyedgecombe 22 hours ago
Comment by zelphirkalt 20 hours ago
This is where asking an LLM for an example is very useful, but ideally, I should be able to find the available fields and their explanation and when to use them at a glance in the docs.
In general the docs are good, just examples could be better.
Comment by phn 21 hours ago
I generally end up with a few core apps with the main data objects that a lot of other "parallel" ones depend on, a bit "star shaped". And then a few "aggregator" apps that cover functionality that needs to work across multiple of these domains. I see it all as an extension of how you think about your data model.
Comment by tclancy 19 hours ago
Comment by phn 18 hours ago
I do what I must in the atomic context, and trigger celery tasks for everything else.
Comment by fmind-dev 20 hours ago
Comment by giancarlostoro 19 hours ago
Comment by harrouet 21 hours ago
I totally understand why the OP would use only FBV, however when writing REST APIs you will want CBV to reuse base classes such as ListView.
Comment by daft_pink 14 hours ago
Comment by zelphirkalt 21 hours ago
(1) It seems whenever I need to adjust how something works, there is some field or method, that I can override, or meta class attribute to set. None of it seems too inflexible. Overriding or changing how things work somehow always feels like someone already thought of this special case I have, and has made it mostly easy to do. Often when I have such a customization case, I have this feeling: "AH, that's how it is supposed to be done in Django." instead of having a feeling of having to fight the framework.
(2) Just being able to use a normal template engine (I always use Jinja2 with Django), instead of having some wannabe HTML lookalike thing. I don't want to have to encode control flow inside HTML attributes. Why then make it look like HTML in the first place, if some JS framework then picks it apart? It is unnecessarily cumbersome to do that, and Django doesn't engage in that.
(3) The ORM is good, and flexible. Some traps for many queries though. But also escape hatches, which let one write ORM calls, that will translate to efficient SQL in most cases.
(4) Django makes it so easy (comparatively) to write a phenomenal searching and ranking function for ones database entities. Check for example the code of my blog [1]. One page of code, very adjustable to ones needs.
(5) Handling of routes is easy. `reverse` is very useful to not have to hardcode routes.
(6) Even when using third-party things like django-allauth it is easy to override templates, without having to modify the dependency itself. With foresight there exists a way to put ones own templates in a place that is discovered before the other package's templates.
(7) Adjustable django admin. I often have some "Tags" in my models, which are many-to-many. For example Posts-TagAssignment-Tag, where TagAssignment is a "throught table". In Django admin one can have a nice little modification [2] to make a very usable widget appear for assigning tags.
In short: It very much gets out of ones way.
[1]: https://codeberg.org/ZelphirKaltstahl/django-website/src/com...
[2]: https://codeberg.org/ZelphirKaltstahl/django-website/src/com...
Comment by tinodb 21 hours ago
It is somewhat explained as a convention or something built-in, but I can't find much about it elsewhere. Is it the author's own convention or am I missing something?
Comment by jbarham 21 hours ago
Comment by stana 20 hours ago
[1]: https://docs.djangoproject.com/en/6.0/ref/contrib/contenttyp...
Comment by thraxil 19 hours ago
Comment by cryo32 22 hours ago
Comment by 0x4d4c 22 hours ago
Comment by panzerboy 22 hours ago
Comment by cryo32 19 hours ago
Ruby is like someone mashed up python and perl whilst on cocaine one day.
Comment by 0x4d4c 22 hours ago
I can take an argument of not buying a Tesla in order to avoid supporting Elons financial empire, but not using Rails because DHH made it is really hard to comprehend.
Comment by owebmaster 21 hours ago
Comment by 0x4d4c 18 hours ago
Comment by brazukadev 18 hours ago
Comment by Nextgrid 21 hours ago
(Do you also check out the blogs/social media of every dev involved in every library you use?)
Comment by BoumTAC 22 hours ago
I don't understand how people can be so out of touch.
Comment by _old_dude_ 21 hours ago
Comment by rob 20 hours ago
Comment by jasoncartwright 19 hours ago
Comment by mystifyingpoi 19 hours ago
Comment by zbentley 19 hours ago
Like, if you have something you regularly spend a lot of money on, it might be worth spending 2min on the Wikipedia article about it’s manufacturer to verify that it’s not made by child slaves or someone who sends all their profits to the KKK or whatever.
Doing that seems like basic prudence for an interconnected world, and a far cry from like … digging around Reddit threads looking for reasons to be outraged.
I have no opinion on DHH. I do think it’s good, actually, that lots of people are incorporating politics into their product use/purchase choices these days. Those decisions always had political consequences, so it’s good that people are now considering that.
Some people definitely have rubrics for making those decisions that I think are stupid, and some people do it dishonestly (e.g. performative public outrage over a random OSS contributor’s transphobic tweet while spending money on Harry Potter shit). But the fact that people are increasingly considering the social context of product use is still good, dumbasses would find other ways to be dumb regardless.
Comment by earthnail 19 hours ago
DHH has always been very outspoken in his opinions. That’s why he bashed Heroku so badly when he introduced Kamal. It’s what makes Rails such a clear minded framework.
In his political blog, he’s raising an issue that’s occupying all of western politics. And he’s very aggressive about it - just how he was very aggressive when he said “stop paying ridiculous amounts for stupid managed clouds”.
Instead of arguing where he’s wrong, people - including the blog post you cite - write “that’s hateful and racist” and refuse to engage beyond that. That is the very shut-up mentality he writes about.
It frustrates me so much to see this here on HN. HN is supposed to be a place to discuss, not blame others. This resistance to engage in a constructive discussion, even if the person with the differing opinion isn’t articulating them well, or has errors in their reasoning that upset you, is super harmful. It’s what gives all these far right parties their rise to power. They occupy the subjects then that their voters have on their mind, because everyone else doesn’t dare to talk about it.
We could have constructive discussions around such topics. But if we don’t, all that happens is that those who don’t feel heard - in this case rightfully so, because we chose not to hear them - will develop more and more extreme ideas.
Comment by blactuary 17 hours ago
Comment by brazukadev 18 hours ago
What a weird statement. He has a platform, people that think his content is hateful and racist don't have a platform. He writes about kicking out normal people living their lives from places that he is not even from. Antagonizing people in position of power with this kind of mentality is what every sane person should do.
Comment by sylario 17 hours ago
He is probably at a KKK level of racism.
Comment by panzerboy 21 hours ago
I know that there are other people contributing to Rails, and that's their choice. Other people stopped contributing once DHH showed his true nature.
Comment by owebmaster 21 hours ago
Comment by explorigin 18 hours ago
Comment by dzonga 17 hours ago
[0]: https://litestar.dev
Comment by sinpif 21 hours ago
Comment by Maxion 22 hours ago
Works incredibly well almost straight out of the box for even quite large applications. Once you start to grow out of it, it's easy to bypass the ORM and write raw sql queries.
You also won't be re-writing your backend every few years, the cost of which techbros often ignore.
Comment by aitchnyu 22 hours ago
Comment by zelphirkalt 20 hours ago
Comment by angusj1 21 hours ago
Comment by stavros 23 hours ago
Comment by weatherlite 22 hours ago
Comment by ustad 21 hours ago
Comment by stavros 22 hours ago
Comment by weatherlite 22 hours ago
Comment by DoctorDabadedoo 21 hours ago
Comment by alexbelyanin 21 hours ago
Comment by songhonglei1985 22 hours ago