0

I have a model charfield which has dynamic choices

class MachineChoices(object):
    def get_machine_choices(self):
        # call external service to get a full list of machines
        ...

    def __iter__(self):
        yield from self.get_machine_choices()

class ExceptionMapping(models.Model):
    machine_id = models.IntegerField(null=True, blank=True, choices=MachineChoices())

My problem is that when I run makemigrations it will generate a migration for the field with all the choices.

How do I get around this without such gigantic migration. Deleting this migration manually each time running makemigrations is a pain in the butt.

Please Note: I am asking why this is happening as I have already asked before.

James Lin
  • 25,028
  • 36
  • 133
  • 233

1 Answers1

1

I had problems with migrations, I solved them by executing different code depending if the current process is related to migration or not, as you can see in this question.

In your case, you could do something like that:

class ExceptionMapping(models.Model):
    import sys
    if 'makemigrations' not in sys.argv and 'migrate' not in sys.argv:
        machine_id = models.IntegerField(null=True, blank=True, choices=MachineChoices())
    else:
        machine_id = models.IntegerField(null=True, blank=True)

I am agree that this solution is a bit hacky, but it works.

albar
  • 3,020
  • 1
  • 14
  • 27
  • thank you for the hint, I was thinking about the same approach but was expecting a proper migration action flag in django, anyway this looks like the best work around so far. – James Lin Mar 28 '19 at 18:36