简体   繁体   English

如何在保存时将整数添加到 Django 模型中的主键字段

[英]How to add integers to primary key field in Django Model at save

In my Django app, I have created a model with the id (primary key) as a CharField of length 6. I am using a custom validator which allows the user to only enter integers only.在我的 Django 应用程序中,我创建了一个 id(主键)作为长度为 6 的CharField的模型。我使用了一个自定义验证器,它只允许用户输入整数。 Is there a way to add zeros before the input if it is less than the "six" character length specified in the field definition.如果输入小于字段定义中指定的“六个”字符长度,是否可以在输入前添加零。

For example, the user enters value 1234 in the primary key field.例如,用户在主键字段中输入值1234 Now I want that at save the pk field value should be saved as 001234 .现在我希望在保存时 pk 字段值应保存为001234

I tried doing that at save but two records are getting created, one with the input by the user and the other with the zero(s) added.我尝试在save这样做,但是正在创建两条记录,一条是用户输入的,另一条是添加了零的。

Is this at all possible to achieve what I am trying to do?这完全有可能实现我想要做的事情吗?

Edit编辑

Here is what I am doing (seems quite low-tech to me though):这是我正在做的事情(虽然对我来说似乎技术含量很低):

class Plant(models.Model):
    plant_id = models.CharField(primary_key=True,..,)
    plant_name = models.CharField(max_length=55, verbose_name="Plant/W.Area")

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if len(self.plant_id) == 4:
            ramp_up_obj_id = '00' + str(self.plant_id)
            self.plant_id = str(ramp_up_obj_id)
        super().save(*args, **kwargs)

The result on save is (as narrated above): For entered value of 1001 , there two records created.保存的结果是(如上所述):对于1001 的输入值,创建了两条记录。 One with 1001 and the other one as 001001 .一个是1001 ,另一个是001001

You can usezfill function before calling super().save method and call super().save() only once.您可以在调用super().save方法之前使用zfill函数并且只调用super().save()一次。

class Plant(models.Model):
    plant_id = models.CharField(primary_key=True,..,)
    plant_name = models.CharField(max_length=55, verbose_name="Plant/W.Area")

    def save(self, *args, **kwargs):
        self.plant_id = str(self.plant_id).zfill(6)
        super().save(*args, **kwargs)

According to this answer here: Django generate custom ID根据这里的答案: Django generate custom ID

With @property (I highly suggest you to go with this instead)使用@property (我强烈建议你改用这个)

@property
def sid(self):
    return "%05d" % self.id

With CharField使用CharField

id = models.CharField(primary_key=True, editable=False, max_length=10)

def save(self, **kwargs):
    if not self.id:
        max = Rate.objects.aggregate(id_max=Max('id'))['id_max'] + 1
        self.id= "{:05d}".format(max if max is not None else 1)
    super().save(*kwargs)

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

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