【问题标题】:How to join Objects in Django with Foreign Keys 2 tables deep如何使用外键连接 Django 中的对象 2 个表深
【发布时间】:2020-10-06 14:10:17
【问题描述】:

我有 2 个模型,每个模型都有 2 个表的外键。我正在尝试将第一张桌子加入第三张桌子。 这是我的模型:

模型 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 的过滤查询中使用来自AppCustomerTpRelcust_vendor_rel 字段

【问题讨论】:

    标签: django join orm


    【解决方案1】:

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

    idcst_bil__appcustomertprel__cust_vendor_rel

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

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2012-10-17
      • 2022-08-02
      相关资源
      最近更新 更多