Reputation: 4636
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
Reputation: 998
There might be a simpler way to accomplish this, but these steps should work:
color
field with null=True
and without the default and the unique=True
.makemigrations
for your app.makemigrations --empty
to create a custom migration for your app. Add a RunPython operation using your random_color()
to populate the new column.color
field to add the default, unique constraint, and remove the null=True
.makemigrations
again.Upvotes: 5