在我的模型中,我有一个班级
class User(AbstractDateTime, AbstractBaseUser, PermissionsMixin, models.Model):
email = models.EmailField(max_length=255, unique=True,blank=False,default='')
first_name = models.CharField(max_length=255, blank=False,default='')
last_name = models.CharField(max_length=255, blank=False,default='')
merchant_id = models.CharField(max_length=255, blank=True,default='')
customer_id = models.CharField(max_length=255, blank=True,default='')
phone_number = models.CharField(max_length=255,blank=False,default='')
zip_code = models.CharField(max_length=10,blank=False,default='')
photo = models.FileField(upload_to='images/users', default=None, blank=True, null=True)
STATUS_TYPES = (('admin', 'admin'),('client', 'client'))
role = models.CharField(max_length=10,choices=STATUS_TYPES,default='client')
reset_key = models.CharField(max_length=255, blank=True,default='')
credits = models.DecimalField(max_digits=5, decimal_places=2,default=0)
is_staff = models.BooleanField(default=0)
is_active = models.BooleanField(default=1)
objects = AuthUserManager()
USERNAME_FIELD = 'email'
def last_seen(self):
return cache.get('seen_%s' % self.user.email)
def online(self):
if self.last_seen():
now = datetime.datetime.now()
if now > self.last_seen() + datetime.timedelta(
seconds=settings.USER_ONLINE_TIMEOUT):
return False
else:
return True
else:
return False
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def __unicode__(self):
return unicode(self.email) or 'not found'
class Meta:
ordering = ["id"]
db_table = "user"
get_latest_by = "created"
在视野中我想调用我的模型的在线方法
users = User.objects.filter()
for user in users:
user.online()
我收到此错误“用户”对象没有属性“用户”
答案 0 :(得分:6)
您的函数last_seen
有错误。你正在做self.user.email
这是不正确的,它应该是self.email
。
此外,执行User.objects.filter()
并不是一种好习惯,因为filter
用于使用sql WHERE
等条件进行查找。如果您想要所有结果,请执行User.objects.all()
。