Django Model Auto Increment Primary Key Based on Foreign Key
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.