2

I want to add a new field to my already existing model called color. I want it to be unique and also want it to be randomly selected by default. So what I do is:

color = models.CharField(max_length=15, default=random_color, unique=True)

My random_color looks like this

def random_color():
"""
Returns:
    [string] : returns a rgb value in hex string
"""
while True:
    generated_color = f'#{random_hex()}{random_hex()}{random_hex()}'
    if not MyModel.objects.filter(color=generated_color):
        return generated_color

I followed a similar logic to what has been provided here.

Now the problem with this approach is that there is no color to begin with to look for.

And I also want my migration to add in a bunch of default random color values to my already existing tables.

How do I fix this?

Prasanna
  • 4,125
  • 18
  • 41

1 Answers1

5

There might be a simpler way to accomplish this, but these steps should work:

  1. Add the new color field with null=True and without the default and the unique=True.
  2. Run makemigrations for your app.
  3. Run makemigrations --empty to create a custom migration for your app. Add a RunPython operation using your random_color() to populate the new column.
  4. Alter the color field to add the default, unique constraint, and remove the null=True.
  5. Run makemigrations again.
HorsePunchKid
  • 848
  • 12
  • 17
  • This is the way to go! I do not know of a simpler way. For a more detailed explanation, see: https://stackoverflow.com/questions/29787853/django-migrations-add-field-with-default-as-function-of-model?rq=2 – Wim Feijen May 01 '23 at 13:44