DavidMM
DavidMM

Reputation: 187

Django: How to randomize choices field of every existing model

I have 100 instances of a Model, but now I've added a new choices Field with a default value. It is working and every instance share the same field, but I want it to be randomize between the X values of the choices.

This is a modified version of my model

class MyModel(models.Model):

    A = 'a'
    B = 'b'
    C = 'c'

    CATEGORIES_CHOICES = (
        (A, 'Ant'),
        (B, 'Buffalo'),
        (C, 'Cat'),
    )
    category = models.CharField(max_length=1, choices=CATEGORIES_CHOICES, default=A)

With that I can go to the shell and type the following:

mymodel = MyModel.objects.get(id=1)
mymodel.category = random.choices(MyModel.CATEGORIES_CHOICES)[0][0]
mymodel.save()

And it works, but can I automatize it to do it in all 100 instances?

Upvotes: 0

Views: 998

Answers (1)

Bast
Bast

Reputation: 369

If it's a 1 time operation just make a for loop

If not try something like this

class MyModel(models.Model):

A = 'a'
B = 'b'
C = 'c'

CATEGORIES_CHOICES = (
    (A, 'Ant'),
    (B, 'Buffalo'),
    (C, 'Cat'),
)
category = models.CharField(max_length=1, choices=CATEGORIES_CHOICES, default=None, blank=True, null=True)

def save(self, *args, **kwargs):
    if not self.category:
        # note sure for the syntax of this random choices
        self.category = random.choices(self.CATEGORIES_CHOICES)[0][0]
    super(MyModel, self).save(*args, **kwargs)

With this solution every time you save "MyModel" with None as category, a random category will be set before the save.

But this is not the best solution for data consistency

Upvotes: 1

Related Questions