简体   繁体   English

Django:如何随机化每个现有模型的选择字段

[英]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. 我有100个Model实例,但是现在我添加了一个带有默认值的新选择字段。 It is working and every instance share the same field, but I want it to be randomize between the X values of the choices. 它正在工作,并且每个实例共享相同的字段,但是我希望它在选项的X值之间随机分配。

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? 它可以工作,但是我可以在所有100个实例中自动化它吗?

If it's a 1 time operation just make a for loop 如果是1次操作,则进行for循环

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. 使用此解决方案,每次将“ MyModel”保存为“无”作为类别时,将在保存之前设置一个随机类别。

But this is not the best solution for data consistency 但这不是确保数据一致性的最佳解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM