访问user Model的三种方式
一、最常规,不定制custom的方式
from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField()
二、custom user
# settings.py AUTH_USER_MODEL = `users.CustomUser`
然后在model这样写
from django.conf import settings from django.db import models class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=50) body = models.TextField()
三、不管是不是定制,通用的写法:get_user_model
# settings.py AUTH_USER_MODEL = `users.CustomUser`
model.py这样写
from django.contrib.auth import get_user_model from django.db import models class Post(models.Model): author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) title = models.CharField(max_length=50) body = models.TextField()
get_user_model()会返回当前使用的用户,不论是定制还是系统默认用户。
AUTH_USER_MODEL
只针对定制用户。