frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

How to Get Foreign Keys Horribly Wrong

https://hakibenita.com/django-foreign-keys
49•Bogdanp•3d ago

Comments

jihadjihad•5h ago
> Django will implicitly add an index on a ForeignKey field unless explicitly stated otherwise.

This is nice to know if you're using Django, but as important to note is that neither Postgres nor SQLAlchemy / Alembic will do this automatically.

rrauenza•4h ago
How can we determine if an index can be satisfied by a constraint index?

For example, does the FK need to be the first field in a unique together?

cogman10•4h ago
This sort of thing hasn't really done much to make me like ORMs.

It seems like a lot of code to generate the tables in the first place and you STILL need to read the output scripts just to ensure the ORM isn't generating some garbage you didn't want.

That seems like a lot of extra effort when a simple migration service (such as liquibase) could do the same work running SQL directly. No question on "which indexes are getting created and why". No deep knowledge of Django interactions with sql. Instead, it's just directly running the SQL you want to run.

teaearlgraycold•4h ago
I would say automatic migration generation isn’t a necessary or particularly important part of an ORM. ORMs are there to map your database relational objects to your client language’s objects.
cjs_ac•4h ago
I think the person you're replying to is arguing for using some sort of database migration library without using an ORM library. It's the same position I came to recently.
teaearlgraycold•3h ago
Yes but they seem to have switched because they didn’t like ORM-generated migration code. I think that’s a bad reason to switch because it wasn’t an important part of ORMs in the first place. Basically, I want to know why they were even using ORMs before.

I don’t want to go without an ORM because I’ll end up making one ad-hoc anyway. I’m not going to do work on raw tuples in my application code.

Tostino•4h ago
I'd call it an anti-feature for most long-lived projects that will end up needing migrations through its lifetime.

I go the liquibase route for migrations, and just use the mapping portion of any ORM.

pphysch•4h ago
Most(?) devs nowadays are introduced to database migration tools as a DX feature.

"Wow, 1-2 command and my app and database are in sync!"

In reality, migration tools are 100% about data loss prevention.

If you do not care about data loss, updating your schema is trivial, just drop everything and create. Dev environments should be stateless anyways, using separate data "fixtures" when needed.

Data loss itself is a highly nuanced topic. Some data is replaceable, some might be protected in a separate store. So I agree that ORMs should challenge the assumption that automatic migration tools need to be part of their kitchen sink.

teaearlgraycold•3h ago
I like that they provide the basic structure of how to apply yet unseen migrations. But they don’t need to generate the SQL at all. You quickly learn to never trust the generated code. It always needs to be manually reviewed.
wagwang•14m ago
The ORM auto migration tools are a 100% a DX feature. Obviously any serious application will have complicated migrations that outgrow the generated sql; doesn't mean its not a nice to have feature for quick iteration.
wvenable•3h ago
I do read my migration scripts generated from an ORM to make sure my source code is correct.

Liquibase starts with "Write your database change code in your preferred authoring tool in SQL, YAML, JSON, or XML." So instead of just having my ORM generate that and I just have to read them to ensure correctness, I have to manually write change scripts instead? I don't see how that's is comparable.

Liquibase could certainly come in after I have some SQL scripts generated from my ORM and do whatever it does.

aidos•3h ago
I’ve done a lot of interviewing and I’ve discovered that many devs (even experienced ones) don’t understand the difference between indexes and foreign keys.

My assumption is that people have used orms that automatically add the index for you when you create a relationship so they just conflate them all. Often they’ll say that a foreign key is needed to improve the performance and when you dig into it, their mental model is all wrong. The sense they have is that the other table gets some sort of relationship array structure to make lookups fast.

It’s an interesting phenomenon of the abstraction.

Don’t get me wrong, I love sqlalchemy and alembic but probably because I understand what’s happening underneath so I know the right way to hold it so things are efficient and migrations are safe.

whyowhy3484939•2h ago
Very strange if you ask me and disturbing. I don't know if I'd let such a dev touch a database. Of course nowadays we just vibe code and YOLO everything, but still. This is making me feel old.
bevr1337•2h ago
> their mental model is all wrong.

Is it? In Postgres, all FK references must be to a column with a PK or unique constraint or part of another index. Additionally, Postgres and Maria (maybe all SQL?) automatically create indexes for PKs and unique constraints. There's a high likelihood that a foreign key is already indexed _in the other table_.

Generally, I agree with your statement. Adding a FK won't magically improve performance or create useful indices. But, the presence of a FK or refactoring to support a FK does (tangentially) point back to that index.

ak39•2h ago
By definition, a FK has to reference a PK in the “parent”.
aidos•52m ago
Not quite. It can reference any combination of columns with a unique index (of with the PK is by definition).
UltraSane•1h ago
Yes. Not understanding the difference means you really don't understand the relational model. It would be like a network engineer not understanding the difference between IP and MAC addresses.
aidos•58m ago
I wasn’t totally clear on my original statement. As you point out, the referenced columns in the referenced table need to have a unique constraint and that’s done with a unique index. My understanding is that this ensures there’s no ambiguity as to which row is referenced and allows for efficient enforcement of the FK constraint.

Django automatically creates an index on the referencing table to ensure that joins are fast. The fact that you have the relationship in the ORM means that’s how you’re likely to access the data so it makes perfect sense.

The mental model mismatch I’ve seen is that people appear to think of the relationship as being on the parent object “pointing” at the child table.

Fishkins•2h ago
Huh, that's interesting. Mixing indexes and FKs is a major conceptual error.

FWIW, I've also asked everyone I've interviewed in the past decade about indexes and FKs. Most folks I've talked to seem to understand FKs. They're often fuzzier on the details of indexes, but I don't recall anyone conflating the two.

aidos•54m ago
I guess it depends on how much time you’ve spent in a relational db. For people who mostly interact with them via an orm, I can see where the confusion comes from.
dakiol•1h ago
Is this for real? I don’t know why anyone would deal with such amount of incidental complexity (django orm) when one can just use plain sql.
twelve40•1h ago
why is this so surprising? every place i worked at, going back probably 6 jobs, was using an ORM (django, hibernate, or even a self-built one), they went on to get acquired by Twitter, Microsoft, Uber etc, so not completely stupid or obscure. Even if you have a personal dislike of ORMs, if you ever work with/for another team with an exiting codebase and a DB, chances are you will have to work with one.
miggol•43m ago
I don't want to defend Django here, surely this should be categorized as a bug. But on the other hand, for this situation to come up you have to be the following:

- The kind of person to dive into the schema and worry about an unnecessary index

- Smart enough to heed Django's warnings and use `Meta.UniqueConstraint`

- Dumb enough to ignore Django's warnings and not use `Meta.Indexes`

I think it's funny that the kind of dev that 100% relies on the ORM and would benefit from this warning would probably never find themselves in this gritty optimization situation in the first place.

That being said, I enjoyed the article and learned something so maybe I'm the target audience and not them.

Asynchrony is not concurrency

https://kristoff.it/blog/asynchrony-is-not-concurrency/
151•kristoff_it•4h ago•104 comments

How to write Rust in the Linux kernel: part 3

https://lwn.net/SubscriberLink/1026694/3413f4b43c862629/
22•chmaynard•1h ago•0 comments

Ccusage: A CLI tool for analyzing Claude Code usage from local JSONL files

https://github.com/ryoppippi/ccusage
14•kristianp•49m ago•4 comments

Shutting Down Clear Linux OS

https://community.clearlinux.org/t/all-good-things-come-to-an-end-shutting-down-clear-linux-os/10716
13•todsacerdoti•27m ago•2 comments

Silence Is a Commons by Ivan Illich (1983)

http://www.davidtinapple.com/illich/1983_silence_commons.html
57•entaloneralie•2h ago•9 comments

Broadcom to discontinue free Bitnami Helm charts

https://github.com/bitnami/charts/issues/35164
81•mmoogle•4h ago•43 comments

Wii U SDBoot1 Exploit “paid the beak”

https://consolebytes.com/wii-u-sdboot1-exploit-paid-the-beak/
63•sjuut•3h ago•7 comments

EPA says it will eliminate its scientific reseach arm

https://www.nytimes.com/2025/07/18/climate/epa-firings-scientific-research.html
58•anigbrowl•1h ago•21 comments

Multiplatform Matrix Multiplication Kernels

https://burn.dev/blog/sota-multiplatform-matmul/
44•homarp•4h ago•16 comments

lsr: ls with io_uring

https://rockorager.dev/log/lsr-ls-but-with-io-uring/
292•mpweiher•11h ago•151 comments

Valve confirms credit card companies pressured it to delist certain adult games

https://www.pcgamer.com/software/platforms/valve-confirms-credit-card-companies-pressured-it-to-delist-certain-adult-games-from-steam/
141•freedomben•8h ago•141 comments

Meta says it wont sign Europe AI agreement, calling it growth stunting overreach

https://www.cnbc.com/2025/07/18/meta-europe-ai-code.html
84•rntn•6h ago•117 comments

Trying Guix: A Nixer's impressions

https://tazj.in/blog/trying-guix
132•todsacerdoti•3d ago•38 comments

AI capex is so big that it's affecting economic statistics

https://paulkedrosky.com/honey-ai-capex-ate-the-economy/
181•throw0101c•4h ago•196 comments

Replication of Quantum Factorisation Records with a VIC-20, an Abacus, and a Dog

https://eprint.iacr.org/2025/1237
57•teddyh•5h ago•14 comments

Show HN: Molab, a cloud-hosted Marimo notebook workspace

https://molab.marimo.io/notebooks
61•akshayka•5h ago•8 comments

Mango Health (YC W24) Is Hiring

https://www.ycombinator.com/companies/mango-health/jobs/3bjIHus-founding-engineer
1•zachgitt•5h ago

CP/M creator Gary Kildall's memoirs released as free download

https://spectrum.ieee.org/cpm-creator-gary-kildalls-memoirs-released-as-free-download
226•rbanffy•13h ago•118 comments

The year of peak might and magic

https://www.filfre.net/2025/07/the-year-of-peak-might-and-magic/
68•cybersoyuz•6h ago•34 comments

Sage: An atomic bomb kicked off the biggest computing project in history

https://www.ibm.com/history/sage
10•rawgabbit•3d ago•0 comments

Show HN: I built library management app for those who outgrew spreadsheets

https://www.librari.io/
43•hmkoyan•4h ago•27 comments

Cancer DNA is detectable in blood years before diagnosis

https://www.sciencenews.org/article/cancer-tumor-dna-blood-test-screening
152•bookofjoe•5h ago•94 comments

A New Geometry for Einstein's Theory of Relativity

https://www.quantamagazine.org/a-new-geometry-for-einsteins-theory-of-relativity-20250716/
71•jandrewrogers•8h ago•1 comments

Show HN: Simulating autonomous drone formations

https://github.com/sushrut141/ketu
12•wanderinglight•3d ago•2 comments

How I keep up with AI progress

https://blog.nilenso.com/blog/2025/06/23/how-i-keep-up-with-ai-progress/
165•itzlambda•5h ago•85 comments

Benben: An audio player for the terminal, written in Common Lisp

https://chiselapp.com/user/MistressRemilia/repository/benben/home
45•trocado•3d ago•3 comments

Making a StringBuffer in C, and questioning my sanity

https://briandouglas.ie/string-buffer-c/
26•coneonthefloor•3d ago•15 comments

Hundred Rabbits – Low-tech living while sailing the world

https://100r.co/site/home.html
214•0xCaponte•4d ago•60 comments

How to Get Foreign Keys Horribly Wrong

https://hakibenita.com/django-foreign-keys
49•Bogdanp•3d ago•23 comments

When root meets immutable: OpenBSD chflags vs. log tampering

https://rsadowski.de/posts/2025/openbsd-immutable-system-logs/
126•todsacerdoti•15h ago•41 comments