Q:

Django Model Auto Increment Primary Key Based on Foreign Key

I'm trying to figure out how to lay out two of my Django models so that when a new model is saved to the database, its primary key is incremented such that it is the next highest value for all records with the same foreign key.
It's much like this question asked, but I'm wondering how you would do it in Django. Here's an excerpt from the question which demonstrates a similar situation:
id | job_id | title
0     1        hi
1     1        hello
2     1        goodbye
0     2        hi
1     2        hello

I know you can't have multiple primary keys in a Django model and you can use unique_together, but the documentation says it uses the equivalent UNIQUE statement in the CREATE statements. Would 
class ModelA(models.Model):
   key = models.PositiveIntegerField(primary_key = True)
   fk = models.ForeignKey(ModelB)

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

in the models work with this answer to accomplish what I'm looking for? The relationship between the models is one ModelA having many ModelBs, but each ModelB having only one ModelA.

A:

Dirk, you have to make some changes to model (if permissible) as Ignacio has said. So, ModelA should now look something like the following.
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 from a method cal_key taking fk as argument. So, define the following cal_key method below 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 method clearly indicates what you actually require.

