Avoiding duplicate objects in Django querysets
johnnymetz.com
Avoiding duplicate objects in Django querysets
1–8 of 8 posts
Re: Avoiding duplicate objects in Django querysets
#2One thing worth mentioning: if you're hitting this problem frequently, it might be worth reconsidering the query patterns themselves. We had a similar issue at work where we kept adding `.distinct()` everywhere, and eventually realized we were doing the filtering wrong upstream.
The PostgreSQL-specific `distinct(*fields)` with the ORDER BY restriction is one of those things that trips people up. The error message isn't great either. "SELECT DISTINCT ON expressions must match initial ORDER BY expressions" is technically correct but doesn't explain why or what to do about it.
Good call recommending Exists as the default approach. It's more explicit about intent too.
Re: Avoiding duplicate objects in Django querysets
#3That being said, I use Django daily for 10 years but I don’t understand the ORM besides basic CRUD. Even a simple group by looks weird.
Writing plain SQL feels easier and more maintainable in the long run.
Re: Avoiding duplicate objects in Django querysets
#4Also, some databases (like clickhouse) allow for `any` joins which avoid producing duplicate rows. For example:
select author.*
from author
inner any join book on (
book.author_id = author.id
and book.title like 'Book%'
)Re: Avoiding duplicate objects in Django querysets
#5Good read, TIL! That being said, I use Django daily for 10 years but I don’t understand the ORM besides basic CRUD. Even a simple group by looks weird. Writing plain SQL feels easier and more maintainable in the long run.
Re: Avoiding duplicate objects in Django querysets
#6Re: Avoiding duplicate objects in Django querysets
#7Nice write up showcasing Exists. I would say, if ORM abstraction “distinct()” is a performance issue, then it’s probably time to switch to SQL. I find it simpler to either use the ORM or the SQL than to bend ORM into SQL.
0: https://dev.mysql.com/doc/refman/8.4/en/group-by-optimizatio...
Re: Avoiding duplicate objects in Django querysets
#8Nice write up showcasing Exists. I would say, if ORM abstraction “distinct()” is a performance issue, then it’s probably time to switch to SQL. I find it simpler to either use the ORM or the SQL than to bend ORM into SQL.
The ORM isn’t the performance issue here, it’s the DB. DISTINCT is a form of GROUP BY, and so it brings with it the various limitations imposed by the RDBMS. For example, look at what MySQL requires to use an index to perform a GROUP BY. 0: https://dev.mysql.com/doc/refman/8.4/en/group-by-optimizatio...