[Answer]-Create a per-master-object id for each object belogning to a master object

1πŸ‘

βœ…

The unique_together is a constraint, not an id-generator.

To achieve what you want, just an integer field to your SecondModel, add this field to your unique_together and override the save method of the model to set the correct value of this field. For instance, you can do something like this:

class SecondModel(models.Model):
    name = models.charField(max_length=30)
    mainmodel = models.ForeignKey(MainModel)
    mainid = models.Integerfield()

    def save(self, *args, **kwargs):
        if not self.mainid:
            self.mainid = SecondModel.objects.get(mainmodel=self.mainmodel).count()+1
        super(SecondModel, self).save(*args, **kwargs)

    class Meta:
        unique_together(("mainmodel","mainid"),)
πŸ‘€Serafeim

0πŸ‘

Firstly, your question text completely contradicts your title. Using unique_together in that way implies that you only want one SecondModel for each individual MainModel: in which case a OneToOne field is more appropriate than a ForeignKey with unique_together.

Secondly, what you are asking is impossible. Primary keys are unique: you can’t have multiple instances of SecondModel all with the same id value, even if they have separate parents.

Perhaps you should explain what problem you are actually trying to solve here.

0πŸ‘

The ids are asigned by model … so if you need any other specification, you will have to make them.

πŸ‘€monobot

Leave a comment