Django如何处理子表中的外键

时间:2012-04-10 17:58:42

标签: django model foreign-keys

我是DJango的新人。我有一个包含三个表的数据库:

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

我有以下型号:

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'

一切都适用于“子组件”模型(参考CRP);在“子组件”的管理中,用户可以下拉CRP并向其添加子组件。

然而,模型“目标”引用模型“子组件”。在“目标”的管理中,我希望用户下拉并选择一个CRP,然后在下拉列表中过滤该CRP的子组件。我怎么能这样做?

非常感谢, 卡洛斯。

1 个答案:

答案 0 :(得分:0)