Premier League Predictor: Django & MySQL — Chapter 5, Exercise 2 ==================================================== TASK Explain why db_persist=True is specifically required for this GeneratedField to work correctly on MySQL, and what real database feature it corresponds to. SOLUTION Django's GeneratedField supports two underlying storage modes, chosen via db_persist: - db_persist=True compiles to a real, physically STORED generated column — the computed value is actually written to disk on every insert or update, exactly like an ordinary column, just with its value derived automatically from the expression instead of supplied directly. - db_persist=False (the default when omitted) compiles to a VIRTUAL generated column instead — the value is computed on read, not stored on disk at all. This distinction matters specifically for MySQL because MySQL's own support for indexing a generated column depends on which of these two kinds it is. A VIRTUAL generated column has real, documented limitations around being indexed directly on older MySQL versions — historically it could only be indexed as part of a secondary index in InnoDB, with real restrictions on primary keys and certain storage engines. A STORED generated column behaves like any other real, materialized column for indexing purposes, with no such caveats. Since unique_key exists purely so a UniqueConstraint can be placed on it, the column has to be reliably indexable — that's the entire point of building it. Choosing db_persist=True sidesteps MySQL's own VIRTUAL-column indexing caveats entirely by making unique_key a real, stored column from the start, at the modest cost of a small amount of extra disk space per row (the value is now genuinely duplicated on disk rather than computed fresh on each read). MySQL has supported STORED generated columns since 5.7, which is why Chapter 1's own MySQL setup didn't need to specify any particular newer MySQL version for this feature specifically to work. WHY THIS WORKS AS AN ANSWER ---------------------------- It distinguishes STORED from VIRTUAL generated columns, explains the real MySQL indexing limitation that makes VIRTUAL columns a worse fit here, and ties db_persist=True directly to the actual reason unique_key needs to be reliably indexable at all.