答案 0 :(得分:8)
models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
address = models.TextField()
......
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
只要在用户表上创建新用户,上述代码就会创建 UserProfile 记录。然后,您可以访问个人资料详细信息,如
address = request.user.profile.address
答案 1 :(得分:1)
get_profile()
方法返回了有关User的其他信息。目前,这些信息可以存储在自定义用户模型中,也可以存储在与用户模型相关的单独模型中。您可以simply adding one2one relation with User model to your custom User model或by subclassing the AbstructUserBase model。
子类化用户模型示例:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
...
One2One与用户模型示例的关系:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)