3 ms·
Django ORM is ActiveRecord pattern, right? This is what I would use Book.objects.filter(author__nationality="Italian", author__state="deceased").values("is
by shabda 7y ago
Django ORM is ActiveRecord pattern, right?
This is what I would use
Book.objects.filter(author__nationality="Italian", author__state="deceased").values("isbn")
This is
- Is one single DB query.
- Completely obvious way to describe what I want to do.
- Only pulls the fields which are needed from the DB.
If you are claiming "the troublesome acriverecord pattern" you need to provide specifics of what can't be done, rather than claim "Don't look too deeply into the code samples for specifics though"
- smoe 7y agoI think as soon you use "values" it is no longer the ActiveRecord pattern since the result is not an object instance representing a single row in the table. I never read a proper specification of ActiveRecord, but it could be that a "pure" implementation doesn't allow for joins? Hence the weird looking example with the nested for loop, which variations of I have seen plenty in real world code. Mostly by people that don't sufficiently understand the ORM or SQL, not because they were sticking to a pattern though. In your example it is obvious what happens in this simple example, but as soon the joins become more complex, it becomes in my opinion quite unwieldy and non obvious what the resulting SQL will be. I had multiple performance problems in the past because of the queries the ORM generated or with memory/cpu usage on the app side.
- LargeWu 7y agoThat's fine. For 95% of the queries you need, ActiveRecord-ish implementations are perfectly performant, and super readable. For the rest, they allow you to drop down to the SQL layer and specify exactly what you want or need.
- smoe 7y agoYes, that is what we do and what I like about SQLAlchemy for Python. We use the ORM for like 90% of cases and drop down to its SQL abstraction underneath the ORM. The last time I used Django a couple of years ago that was one of the bigger pains for me: It was either the Django ORM capabilities or raw SQL, not much in between. Or maybe I was just unaware of how to do it better.