无法转换' DeferredAttribute'隐含地反对str

时间:2016-09-15 23:35:55

标签: django python-3.x pycharm

当Iam试图获得学生的学位并使用该代码执行返回值时:

from django.db import models

# Create your models here.


class Student(models.Model):
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=15)
    age = models.IntegerField(default=0)
    birth_date = models.DateTimeField()

    def __str__(self):
        return self.first_name + " " + self.last_name


class Degree(models.Model):
    student_id = models.ForeignKey(Student, on_delete=models.CASCADE)
    student_subject = models.CharField(max_length=150)
    student_degree = models.IntegerField(default=0)

    def __str__(self):
        return self.student_subject + " " + Student.last_name

我收到了上述错误消息。 这是整个Django代码:

TypeError at /admin/sellingportal/degree/

Can't convert 'DeferredAttribute' object to str implicitly

Request Method:     GET
Request URL:    http://127.0.0.1:8000/admin/sellingportal/degree/
Django Version:     1.10.1
Exception Type:     TypeError
Exception Value:    

Can't convert 'DeferredAttribute' object to str implicitly

Exception Location:     C:\Users\Muham\PycharmProjects\managementsite\managementstudio\sellingportal\models.py in __str__, line 22
Python Executable:  C:\Python34\python.exe
Python Version:     3.4.4
Python Path:    

['C:\\Users\\Muham\\PycharmProjects\\managementsite\\managementstudio',
 'C:\\Windows\\SYSTEM32\\python34.zip',
 'C:\\Python34\\DLLs',
 'C:\\Python34\\lib',
 'C:\\Python34',
 'C:\\Python34\\lib\\site-packages']

Server time:    Fri, 16 Sep 2016 01:04:08 +0200

错误正在发生,因为我试图继承上述类Student的返回 这是错误信息:

$.ajax({
    type: "POST",
    url: '@Url.Action("themess","file")', // instead of  '@("/file/two/themess")',
    data: {'sText': "Message"}, // instead of 'sText=Message',
    success: function() {
      alert('success');
    },
    failure: function(response) {
      alert(response.d);
    }
  });
});

1 个答案:

答案 0 :(得分:3)

只需将其更改为:

def __str__(self):
    return self.student_subject + " " + self.student_id.last_name

一切都应该没问题。

您无法设置Student.last_name,因为您必须显示从哪个对象显示姓氏。