[Fixed]-Django Model Auto Increment Primary Key Based on Foreign Key

13👍

You have to make some changes to the model (if possible). So, ModelA should look something like this

class ModelA(models.Model):
    key = models.PositiveIntegerField()
    fk = models.ForeignKey(ModelB)

    def Meta(self):
        unique_together = ("key", "fk")

    def save(self, *args, **kwargs):
        key = cal_key(self.fk)
        self.key = key
        super(ModelA, self).save(*args, **kwargs)

As, you can see, I have overridden the default save method to calculate the key value in a cal_key function that takes fk as an argument. So, define the cal_key function in the models file.

def cal_key(fk):
    present_keys = ModelA.objects.filter(fk=fk).order_by('-key').values_list('key', flat=True)
    if present_keys:
        return present_keys[0]+1
    else:
        return 0

The cal_key function clearly indicates what you actually require.

0👍

Jason Ennio’s answer will not let you update the model, since the super(ModelA, self).save(*args, **kwargs) is being controlled by the ‘if’ statement.

Updated ‘save’ method (indentation) to prevent the model from updating the ‘key’ every time you make an update:

class ModelA(models.Model):
key = models.PositiveIntegerField()
fk = models.ForeignKey(ModelB)

def Meta(self):
    unique_together = ("key", "fk")

def save(self, *args, **kwargs):
    if self._state.adding is True:
        key = cal_key(self.fk)
        self.key = key
        super(ModelA, self).save(*args, **kwargs)

Leave a comment