2

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. 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. Now I want that at save the pk field value should be saved as 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.

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. One with 1001 and the other one as 001001.

shaan
  • 351
  • 2
  • 15
  • Could you include your code in your question? It might be that you're close to what you need to do - it sounds like it should be possible - but there may be a bug in your code that people can help you fix. – bouteillebleu Aug 29 '20 at 16:03

2 Answers2

3

You can use zfill function before calling super().save method and call super().save() only once.

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)
mehrdadep
  • 972
  • 1
  • 15
  • 37
-1

According to this answer here: Django generate custom ID

With @property (I highly suggest you to go with this instead)

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

With 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)
Dimitar
  • 460
  • 4
  • 12