django.db.models.Model无法访问属性

时间:2016-05-10 01:42:46

标签: python django model

首先我创建了一个Employee类,但是当我按类名访问它的属性时,例如Employee.user_name,它引发了一个错误,我不知道为什么:

from django.db import models
import uuid

class Employee(models.Model):

    employee_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)    
    user_name = models.CharField(max_length=30)
    pwd = models.CharField(max_length=50)

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    entry_date = models.DateTimeField(auto_now=True, editable=False)

    def __str__(self):
        return self.user_name

the error is below:
>>> Employee.user_name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: type object 'Employee' has no attribute 'user_name'
>>>

1 个答案:

答案 0 :(得分:1)

你的班级里面有很多项目。您需要通过调用#34; pk&#34;来告诉模型您想要的实例。或其他独特的领域。

user = Employee.objects.get(pk=id)
user.user_name