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:
JavaScript
x
10
10
1
class DeviceControl(models.Model):
2
vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
3
id = models.AutoField(primary_key=True)
4
name = models.CharField(max_length=100)
5
description = models.CharField(max_length=1000)
6
position = model.[what do I write here to make it auto generated or equal to id]
7
8
def __str__(self):
9
return self.name
10
please help me to solve this.
Advertisement
Answer
You can override the save
method to set the initial value of position
:
JavaScript
1
18
18
1
class DeviceControlPolicy(models.Model):
2
vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE)
3
id = models.AutoField(primary_key=True)
4
name = models.CharField(max_length=100)
5
description = models.CharField(max_length=1000)
6
position = models.IntegerField(blank=True, null=True)
7
8
def __str__(self):
9
return self.name
10
11
def save(self, *args, **kwargs):
12
super().save(*args, **kwargs)
13
14
if self.position == None:
15
self.position = self.id
16
# You need to call save two times since the id value is not accessible at creation
17
super().save()
18