How to identify if a field's choices have changed in django model?

Viewed 145

I have a model like this:

class MyModel(models.Model):
    status_choices = (
        ('in_progress', 'In Progress'),
        ('in_review', 'In Review'),
        ('active', 'Active'),
    )
    # I want to detect when these choices are changed and trigger a function

    status = models.CharField(choices=status_choices, max_length=20, blank=True)
    # other model fields

Here the status choices can be changed, and I want to detect if the choices have changed and then trigger a function call.

I know there is post_init listener, but how can I compare my cuurent choices with the previous choices when initializing the model?

1 Answers

In that case, one typically writes a model, like MyModelStatus, and work with a ModelChoiceField instead.

so something like:

class MyModelStatus(models.Model):
    name = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.name

class MyModel(models.Model):
    status = models.ForeignKey(MyModelStatus, on_delete=models.PROTECT)
Related