0

Here is a class from models.py:

class Shop(models.Model):
    ...
    code = models.CharField(max_length=4, default=generate_random_code())

As you can imagine, generate_random_code() always return a different string.

The problem is, Django migration engine is lost because everytime I make a python manage.py makemigrations, I get a new modification Alter field tablet_code on shop. I suppose this is because the function is executed, but it should not, so Django thinks I modified the code.

How would you solve this? Thanks.

David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

5

As per the docs you can pass a callable

class Shop(models.Model):
    ...
    code = models.CharField(max_length=4, default=generate_random_code)

..but don't call it, like you're currently doing, or you have the problem you found (the random number generated once when you model is imported but changing each time you run your app)

instead by passing the callable itself migrations should work and you will get a new value each time you create an instance

Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • 4
    This change doesn't only fix the problem with the migration, it fixes a bug in your code; at the moment, the `generate_random_code` is called once when your `models.py` is imported, so multiple `shop` instances will end up with the same code. Passing the callable means that `generate_random_code` is called for each `shop` instance. – Alasdair Jul 06 '15 at 16:19
  • You're both right :) I had this problem too. Thanks a lot. – David Dahan Jul 06 '15 at 16:36