[Answer]-Is it possible to enumerate identical instances of a model?


Something like this could be a good place to start:

from django.db.models import F

class Input(models.Model):
  type = models.ForeignKey("signal")
  component_type = models.ForeignKey("component_type")
  number = models.IntegerField(default=0)

  def save(self, *args, **kwargs):
    if not self.pk:
      self.number = Input.objects.filter(component_type_id=self.component_type_id, type=self.type_id).count() + 1
    super(Input, self).save(*args, **kwargs)

  def delete(self, *args, **kwargs):
    Input.objects.filter(component_type_id=self.component_type_id, type=self.type_id, number__gt=self.number).update(number=F('number')-1)
    super(Input, self).delete(*args, **kwargs)

  def __unicode__(self):
        return "%s - %s" % (self.component_type, self.type, self.number)

We override the delete method to ensure that when an input gets deleted, all inputs with a higher number get a new correct number.

Some notes:

1) Please don’t shoot if this doesn’t work as is, the code is a sketch

2) I took the liberty of capitalizing model names, it’s a standard practice which you could also adopt

3) In the delete method I use the update method to update the appropriate inputs at once without generating db overhead (one query). If this doesn’t work exactly as is, you should still work on that direction

4) The presented unicode method does not explicitly use the component_type.name and type.name properties, but calls the corresponding unicode methods of each model (you might change the ComponentType’s unicode in the future and Input will display the new version)

Leave a comment