Last active
May 3, 2025 13:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/.