Opened 4 years ago

Last modified 4 years ago

#32726 closed New feature

Enforce database level constraints for fields with limited choices — at Version 1

Reported by: Eerik Sven Puudist Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: validation database constraints
Cc: Eerik Sven Puudist Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Eerik Sven Puudist)

When I define a CharField, for example this one from the official docs:

year_in_school = models.CharField(max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN)

a regular VARCHAR field will be defined in the database with no constraints preventing me from inserting other strings to it when I interact directly with the database bypassing the Django layer.

This would compromise data integrity and lead to a state where an unforeseen string is stored in that field which the application would not be able to properly handle.

To prevent such a inconsistent state, I propose that one of the following restrictions would be implemented (the choice might be database specific):

  • add a CHECK constraint to the field which would ensure that the value falls into the range of acceptable choices
  • use the enum datatype to declare acceptable choices
  • create an auxiliary table to store the acceptable choices and add a foreign key constraint to the field

Change History (1)

comment:1 by Eerik Sven Puudist, 4 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top