Django how to deal with foreign keys in child tables

I am new in DJango. I have a database with three tables:

> -CRP
>  - SubComponents of a CRP
>     - Objectives of a SubComponent of a CRP.

I have the following models:

class period(models.Model):
    period_code = models.IntegerField(primary_key=True,verbose_name='Period code')
    period_desc = models.CharField(max_length=45,verbose_name='Period description')
    period_current = models.IntegerField(verbose_name='Current period')
    def __unicode__(self):
        return self.period_desc
    class Meta:
        db_table = 'period'

class crp(models.Model):
    crp_code = models.CharField(max_length=3,primary_key=True,verbose_name='CRP code')
    crp_desc = models.CharField(max_length=45,verbose_name='CRP description')
    def __unicode__(self):
        return self.crp_desc
    class Meta:
        db_table = 'crp'

class subcomponent(models.Model):
    crp_code = models.ForeignKey(crp,db_column='crp_code',related_name='subcomponent_crp_code',to_field='crp_code',primary_key=True,verbose_name='CRP code')
    subc_code = models.CharField(max_length=3,primary_key=True,verbose_name='SubComponent Code')
    subc_desc = models.CharField(max_length=45,verbose_name='SubComponent Description')
    def __unicode__(self):
        return self.subc_desc
    class Meta:
        db_table = 'subcomponent'

class objective(models.Model):
    crp_code = models.ForeignKey(subcomponent,db_column='crp_code',related_name='objective_crp_code',to_field='crp_code',primary_key=True,verbose_name='CRP code')
    subc_code = models.ForeignKey(subcomponent,db_column='subc_code',related_name='objective_subc_code',to_field='subc_code',primary_key=True,verbose_name='SubComponent Code')
    obj_year = models.ForeignKey(period,db_column='obj_year',related_name='objective_obj_year',to_field='period_code',primary_key=True,verbose_name='Objective year')
    obj_code = models.CharField(max_length=7,primary_key=True,verbose_name='Objective code')
    obj_desc = models.CharField(max_length=45,verbose_name='Objective description')
    def __unicode__(self):
        return self.obj_desc
    class Meta:
        db_table = 'objective'

All works fine for the "subcomponent" model (reference to CRP); in the administration of "subcomponent" the user can pull down a CRP and add a subcomponent to it.

However, the model "objective" reference the model "subcomponent". In the administration of "objective" I would like the user to pull down and select a CRP, then filter the subcomponents of that CRP also in a pull down list. How can I do this?

Many thanks, Carlos.


Take a look on django-smart-selects

Need Your Help

How can I tell if eager loading is working?

ruby-on-rails eager-loading nested-resources

So I've got a forum thread full of posts, and I want to eager load the users from the posts and those users roles, to reduce the total number of database queries (which seems to be the best way to do