Proposal: Add warning for db_default that either doesn't resolve output_field or resolve to something not matching field.

Following on from discussion on Ticket 35149


Currently setting db_default to something that resolves to a type other than the field on which its specified is accepted by makemigrations, but will error during migration. See below for examples.


Add a warning to resolve db_default to check whether it’s resolvable and matches the type of the field. This would a.) prevent mismatched types and b.) catch unresolvable expressions which could be problematic.


(excuse the pg-only examples)

class Foo(Model):

    # postgres raises syntax error
    # output_field would be CharField
    mismatched_type = IntegerField(db_default="asdf")

    # psycopg cannot adapt dictionaries
    # output_field is unknown: types cannot be resolved from dictionaries
    unknown_type = JSONField(db_default=Value({'foo': 'bar'}))

    # postgres raises syntax error
    # output_field cannot be inferred from mixed types
    unresolvable_type = IntegerField(db_default=Value(1) + Value('a'))

    # postgres/psycopg2 accepts this
    mismatched_type_2 = IntegerField(db_default="1")

This would be great. I imagine it will need a database connection to correctly resolve though. For example, a default of "1" should work for an IntegerField due to SQL’s type casting. That would make this a database system check, and they don’t run in many situations right now: #32264 (Run database checks by default in some scenarios) – Django

1 Like