You need to enable JavaScript to run this app. Django报错AttributeError: ApplicantEducation对象无'_state'属性 求排查
优惠活动
大模型
产品
解决方案
定价
更多

Django报错AttributeError: ApplicantEducation对象无'_state'属性 求排查

报错信息

AttributeError: 'ApplicantEducation' object has no attribute '_state'

问题成因
  • _state是Django模型类内置的核心属性,由父类django.db.models.Model的默认__init__方法负责初始化,用来标记当前模型实例的生命周期状态(是否已持久化到数据库、是否待保存、是否已删除等),所有数据库CRUD操作都会依赖这个属性执行。
  • 你自定义重写了ApplicantEducation类的__init__方法,没有在自定义方法中调用父类的初始化逻辑,完全覆盖了父类原本的初始化流程,导致_state属性根本没有被创建,后续执行数据库操作时就会触发属性不存在的报错。
  • 你编写的自定义__init__本身存在逻辑错误:方法内直接取ProfileInfo.info_id、DegreeDetails.id这类类属性值,既没有使用传入的参数,也无法正确关联具体的外键实例,完全不符合模型的设计逻辑。
  • 额外的代码问题:
    • FloatField不存在max_length参数(该参数仅为CharField等字符字段的配置项),属于冗余配置。
    • 设置blank=True的日期字段如果允许无值,需要同步配置null=True,否则数据库层会触发非空约束报错。
    • 字段affilation_with为拼写错误,正确拼写为affiliation_with,建议修正避免后续维护歧义。
解决方案

Django的模型初始化逻辑已经内置了实例创建、属性绑定的完整能力,完全不需要手动重写__init__方法——直接删除自定义的错误__init__逻辑即可,Django默认就支持通过关键字参数传入外键实例、字段值创建模型对象,示例用法:

# 正确的实例创建方式,无需自定义__init__
education_obj = ApplicantEducation(
    applicant_info=ProfileInfo.objects.get(info_id=xxx),
    degree_details=DegreeDetails.objects.get(id=yyy),
    marks_percentage=88.5,
    institute_name="某某理工大学",
    affiliation_with="省教育厅",
    date_completion="2020-06-30"
)
education_obj.save()

修正后的模型定义参考:

from django.db import models

class ApplicantEducation(models.Model):
    applicant_info = models.ForeignKey(ProfileInfo, on_delete=models.CASCADE)
    degree_details = models.ForeignKey(DegreeDetails, on_delete=models.CASCADE)
    marks_percentage = models.FloatField(default=0.0)
    institute_name = models.CharField(max_length=100)
    affiliation_with = models.CharField(max_length=50)
    date_completion = models.DateField(auto_now_add=False, blank=True, null=True)

    def __str__(self):
        return str(self.applicant_info)

如果确实需要实现自定义的初始化逻辑,重写__init__时必须在方法第一行透传参数调用父类的__init__,保证内置属性完成初始化,示例结构:

def __init__(self, *args, **kwargs):
    # 必须先调用父类初始化,完成_state等内置属性的创建
    super().__init__(*args, **kwargs)
    # 后续再编写自定义的初始化逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 16:57:02