There are two parts of this question for following situation:
I will use example to describe the question:
These are my django models:
class Zone(models.Model):
zone_name = models.CharField(max_length = 10)
zone_number = models.CharField(max_length = 10)
class Meta:
ordering = ('zone_name',)
def __unicode__(self):
return self.zone_name
class Stage(models.Model):
stage_number = models.CharField(max_length = 10)
stage_name = models.CharField(max_length = 10)
zones = models.ManyToManyField(Zone, through='ZoneStage')
class Meta:
ordering = ('stage_number',)
def __unicode__(self):
return self.stage_number
@property
def value(self):
return ZoneSubStage.objects.filter(substage__stage=self).aggregate(Sum('value')).get('value__sum', 0)
class ZoneStage(models.Model):
zone = models.ForeignKey(Zone)
stage = models.ForeignKey(Stage)
value = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ('zone',)
def __unicode__(self):
return '%s %s' % (self.zone, self.stage)
class SubStage(models.Model):
sub_name = models.CharField(max_length=10)
stage = models.ForeignKey(Stage)
zones = models.ManyToManyField(Zone, through='ZoneSubStage')
def __unicode__(self):
return self.sub_name
class ZoneSubStage(models.Model):
zone = models.ForeignKey(Zone)
substage = models.ForeignKey(SubStage)
value = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return '%s %s' % (self.zone, self.substage)
QUESTION 1: How to create automatically new ZoneStage instances for all related Stages if I create manually new Zone instance ?
e.g. I have following Stage instances: S1, S2, S3, S4 and I create new Zone instance "A". So, I want to create automatically new ZoneStage instances AS1, AS2, AS3, AS4 IF such instance has not existed already ?
QUESTION 2: This is the extension to Question 1. If I create new Zone I want to create automatically ZoneStage instances as described in Question 1 plus I want to create automatically ZoneSubStage instances for all SubStages in all Stages if such ZoneSubStage instance has not existed already.
I do not know how to start with it. I though I should read maybe about post_save() first ?
Now you add Stage Model in this case to access zone model with stage you can use zones or in zone you can use stage_set ok
now in ZoneStage you can access stage with stage (if you can access stage you can access zone). – Mbambadev Aug 29 '15 at 19:39