Skip to content

Instantly share code, notes, and snippets.

@adamghill
Last active May 3, 2025 13:13
Show Gist options
  • Save adamghill/856ca89a5548214c7d74083820723190 to your computer and use it in GitHub Desktop.
Save adamghill/856ca89a5548214c7d74083820723190 to your computer and use it in GitHub Desktop.
A field for `IntegerChoices` which does not generate a new migration when the choices change
class IntegerChoicesField(models.IntegerField):
"""A field for `IntegerChoices` where changing the choices does not generate a new migration. To be used instead of an `IntegerField`.
Based on a suggestion from https://mastodon.social/@bmispelon at https://mastodon.social/@bmispelon/114438157173090099.
"""
def deconstruct(self):
deconstructed_field = super().deconstruct()
if len(deconstructed_field) >= 4 and "choices" in deconstructed_field[3]:
# Remove the `choices` from the dictionary so that new migrations are not created when the choices are modified.
del deconstructed_field[3]["choices"]
return deconstructed_field
"""
Example usage
"""
class Suit(models.IntegerChoices):
CLUB = (1, "Club")
DIAMOND = (2, "Diamond")
HEART = (3, "Heart")
SPADE = (4, "Spade")
class Card(models.Model):
suit = IntegerChoicesField(choices=Suit.choices)
@adamghill
Copy link
Author

Another (better?) approach is to use an intermediate function for choices as explained in detail here: https://adamj.eu/tech/2025/05/03/django-choices-change-without-migration/.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment