如何使用外键连接 Django 中的对象 2 表深

How to join Objects in Django with Foreign Keys 2 tables deep

我有 2 个模型,每个模型都有指向 2 tables 的外键。我正在尝试加入第一个 table 到第三个。 这是我的模型:

模型 1:

class AppBillingBil(models.Model):
    id_bil = models.AutoField(primary_key=True)
    idtrp_bil = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_bil', blank=True,
                                  null=True)
    idcst_bil = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_bil')
    idbtp_bil = models.ForeignKey(AppBillingTypeBtp, models.DO_NOTHING, db_column='idbtp_bil')



    class Meta:
        db_table = 'app_billing_bil'
        ordering = ['id_bil']

模型 2:

class AppCustomerCst(models.Model):
    id_cst = models.AutoField(primary_key=True)
    is_active_cst = models.BooleanField()
    name_cst = models.CharField(max_length=50, blank=True, null=True)

模型 2:

class AppTradingPartnerTrp(models.Model):
    id_trp = models.AutoField(primary_key=True)
    tpid_trp = models.CharField('TPID', max_length=50, blank=True, null=True)
    name_trp = models.CharField('Name', max_length=50)

需要的最终模型:

class AppCustomerTpRel(models.Model):
    id_rel = models.AutoField(primary_key=True)
    idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel')
    idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_rel')
    cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True)

我需要加入以下条件: idtrp_bil__id_trp = idtrp_rel idcst_bil__id_cst = idcst_rel

而且我需要能够在 AppBillingBil

的过滤器查询中使用 AppCustomerTpRel 中的 cust_vendor_rel 字段

阅读此处的文档后:https://docs.djangoproject.com/en/3.0/topics/db/queries/#spanning-multi-valued-relationships 我尝试了这个,并且成功了:

idcst_bil__appcustomertprel__cust_vendor_rel

我意识到我需要在值抓取中包含目标模型名称。