models.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from django.db import models
  2. from django.contrib.auth.models import User
  3. # 引入内置信号
  4. from django.db.models.signals import post_save
  5. # 引入信号接收器的装饰器
  6. from django.dispatch import receiver
  7. # 用户信息
  8. class Profile(models.Model):
  9. # 对应django自带的user
  10. user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
  11. # 电话
  12. phone = models.CharField(max_length=20, blank=True)
  13. # 个人简介
  14. bio = models.TextField(max_length=500, blank=True)
  15. # 头像
  16. avatar = models.ImageField(upload_to='avatar/%Y%m%d/', blank=True)
  17. def __str__(self):
  18. return 'user {}'.format(self.user.username)
  19. # 设备表
  20. class Devices(models.Model):
  21. # 对应django自带的User
  22. user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='devices')
  23. # 设备登录时间
  24. last_login_time = models.DateField(auto_now=True)
  25. # 设备码
  26. device_uid = models.CharField(max_length=100, blank=False)
  27. # 登录凭证
  28. token = models.CharField(max_length=100, default='233', blank=False)
  29. # 信号接收函数,每当新建User实例的时候自动调用
  30. @receiver(post_save, sender=User)
  31. def create_user_profile(sender, instance, created, **kwargs):
  32. if created:
  33. Profile.objects.create(user=instance)
  34. # 信号接收函数,每当更新User实例的时候自动调用
  35. @receiver(post_save, sender=User)
  36. def save_user_profile(sender, instance, **kwargs):
  37. instance.profile.save()