You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django使用非主键字段关联的外键无法访问关联模型实例怎么办

问题根因

Django的ForeignKey字段默认会关联目标模型的主键,你当前equiptment表中存储的tech_system_code值是tech_system模型的tech_system_code字段值,而非tech_system模型的主键id_tech_system的值,导致关联查询时匹配不到对应记录。


解决步骤

  1. 修改equiptment模型的外键定义,显式指定关联字段为tech_system的tech_system_code:
class equiptment(models.Model):
    id_thietbi = models.BigAutoField(db_column='ID_thietbi', primary_key=True)
    # 新增to_field参数指定关联目标表的非主键字段
    tech_system_code = models.ForeignKey(
        'tech_system', 
        models.DO_NOTHING, 
        db_column="tech_system_code", 
        to_field='tech_system_code',
        blank=True, 
        null=True
    )

    class Meta:
        managed = False
        db_table = 'equiptment'

因为你的模型设置了managed = False,修改模型代码后不需要执行makemigrations和migrate操作,不会变更实际表结构。

  1. 验证数据一致性
    修改完成后先在Python Shell执行以下代码确认对应关联记录存在:
# 确认tech_system表中存在tech_system_code为'530'的记录
print(tech_system.objects.filter(tech_system_code='530').exists())

如果返回False说明是实际数据缺失,需要先补全对应tech_system记录,或者清理equiptment表中无效的外键值。

  1. 可选:避免无关联数据时报错
    如果业务允许存在无有效关联的记录,可以在取值时增加容错处理:
# 关联不存在时返回None,不会抛出异常
system_descript = getattr(obj1.tech_system_code, 'system_descript_short', None)

内容的提问来源于stack exchange,提问作者QuangNA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:45:02