Prasanna
Prasanna

Reputation: 4636

migration trouble with unique random default value in model django

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?

Upvotes: 2

Views: 1090

Answers (1)

HorsePunchKid
HorsePunchKid

Reputation: 998

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.

Upvotes: 5

Related Questions