【问题标题】:AttributeError: 'ApplicantEducation' object has no attribute '_state'AttributeError:“ApplicantEducation”对象没有属性“_state”
【发布时间】:2021-06-08 06:43:57
【问题描述】:

这就是我构建模型的方式:

Model.py

    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(max_length=5, default=0.0)
        institute_name = models.CharField(max_length=100)
        affilation_with = models.CharField(max_length= 50)
        date_completion = models.DateField(auto_now_add=False, blank=True)
    
        def __str__(self):
            return str(self.applicant_info)
    
        def __init__(self, applicant_info = None, degree_details = None):
            applicant_info = ProfileInfo.info_id
            degree_details = DegreeDetails.id

任何人,谁能解决这个问题??

【问题讨论】:

    标签: python-3.x django django-models django-views django-templates


    【解决方案1】:

    您正在覆盖模型的 __init__ 而没有调用 Base 类的 __init__,例如您需要使用super 显式调用它:

    class ApplicantEducation(models.Model):
        # fields
        # ...
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # ...
    

    我不知道你对传递给构造函数的 applicant_infodegree_details 参数做了什么(可能你想将它们分配给模型的相应字段)

    【讨论】:

    • 是的,我想将它们分配给您模型的相应字段。