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

Django中外键关联模型的数据互访问题求助

Django外键关联数据访问解决方案

一、从Current_tests实例获取关联的product_name

Current_tests中的product字段是指向Products的外键,每个Current_tests对象可直接通过.product属性拿到关联的Products实例,再访问其product_name字段即可:

# 根据id获取Current_tests实例并取product_name
ct = Current_tests.objects.get(id=1)
product_name = ct.product.product_name

# 根据stagecode获取Current_tests实例并取product_name
ct = Current_tests.objects.get(stagecode="UPDATE REQUIRED")
product_name = ct.product.product_name

二、根据product_name获取所有关联的stagecode

从Products到Current_tests属于反向关联,Django默认生成的反向关联属性为小写模型名_set(即current_tests_set),通过它可获取该产品下所有Current_tests实例,再提取stagecode:

# 先根据product_name获取Products实例
prod = Products.objects.get(product_name="目标产品名称")

# 方式1:遍历提取stagecode
related_tests = prod.current_tests_set.all()
stagecodes = [test.stagecode for test in related_tests]

# 方式2:用values_list直接提取(更高效)
stagecodes = prod.current_tests_set.values_list('stagecode', flat=True)

纠正你之前的错误

你遇到的AttributeError: 'Current_tests' object has no attribute 'product_name_set'源于两个误区:

  1. 方向错误:_set属性是给被关联的主模型(如教程中的Question)使用的,外键所在的Current_tests无需用_set,直接通过.product访问关联对象即可。
  2. 属性名错误:反向关联的属性名基于模型名(小写),而非字段名。Products的反向关联是current_tests_set,不是product_name_set。

可选优化:自定义反向关联名称

如果觉得current_tests_set不够直观,可在定义外键时通过related_name指定自定义名称:

class Current_tests(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE, related_name='tests')
    no_samples = models.IntegerField(default=0)
    stagecode=models.CharField(max_length=30,default="UPDATE REQUIRED")

    def __str__(self):
        return self.stagecode

之后可通过更简洁的方式访问:

prod = Products.objects.get(product_name="目标产品名称")
related_tests = prod.tests.all()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:47:07