Skip to content
Advertisement

How to add Two auto-generated field in one model in Django

I am in need to create two auto-generated fields: 1st field is ID and I am taking the position that is equivalent to id or we can say it is also an auto-generated field in the model.

here is the code which I am integrating:

class DeviceControl(models.Model):
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    position = model.[what do I write here to make it auto generated or equal to id]

    def __str__(self):
        return self.name

please help me to solve this.

Advertisement

Answer

You can override the save method to set the initial value of position:

class DeviceControlPolicy(models.Model):
    vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=1000)
    position = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
       super().save(*args, **kwargs)
       
       if self.position == None:
          self.position = self.id
          # You need to call save two times since the id value is not accessible at creation
          super().save()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement