3 ms·
Employee.objects.filter(boss__salary__lte=F('salary')) Find me employee objects which have a boss salary less than or equal to the salary.
by dalore 13y ago
Employee.objects.filter(boss__salary__lte=F('salary'))
Find me employee objects which have a boss salary less than or equal to the salary.
- PeterisP 13y agoOut of curiosity, would the ORM map to the same SQL query? Or would it request all employee-boss pairs and filter them outside of the DB? There's a huge performance difference involved.
- damon_c 13y agoI believe Django would do this as a single query.
- metaphorm 13y agothis is a good question. my experience with the django ORM is that in general it resolves any call to an ORM method into SQL and nothing else, but it is not guaranteed to generate the most optimal SQL. It is however, a somewhat common practice of django devs to to do some post-processing on a queryset in Python. totally acceptable for small querysets with complicated logic, but, yeah, obviously unacceptable for large performance critical queries.
- freework 13y agoPotentially huge performance difference. For the 99% use case, the performance hit fo the ORM is not significant enough to matter. Most projects have many tables, but only one table that actually needs to have any speed optimizations. That one table can go in NoSQL and the rest can be handled by a ORM.
- dalore 13y agoIt will only be one query. The django orm won't do any filtering outside the DB that is up to you.
- jschmitz28 13y agoIt does not apply to the first question, but how does the ORM handle joined columns from other tables? Is it embedded somewhere in the returned object? The best way I could think to handle this using an ORM would be for the object to contain a set of arbitrary key/value pairs to contain joined columns but it seems like a hack.
- megaman821 13y agoIt is fetched dynamically e.g. employee.boss.department. That will usually cause two more queries to the database. You can use select_related and prefetch_related so that these objects will be loaded into the ORM in one or two queries.