Tom*_*net 3 python django django-models django-users
I am building a django web app with a custom user model which extends the AbstractBaseUser. In one of my models I need to use this custom user model:
from accounts.models import User
class History(models.Model):
user = models.ForeignKey(User)
job = models.ForeignKey(Job)
Run Code Online (Sandbox Code Playgroud)
When I try to run the python manage.py makemigrations command this error message is outputted:
ImportError: cannot import name User
Run Code Online (Sandbox Code Playgroud)
In my settings.py I do the following to let django know that there is a custom user model:
AUTH_USER_MODEL = "accounts.User"
Run Code Online (Sandbox Code Playgroud)
I am puzzled as to what I am doing wrong. Surely there must be a way to import this model that I do not know of. How do I fix this?
I have tried to use the get_user_model() method, however it doesn't work in the model as the models haven't loaded yet. This is therefore not a solution. Any other ideas?
Thank you in advance.
You can do as follows:
from django.conf import settings
class History(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
job = models.ForeignKey(Job)
Run Code Online (Sandbox Code Playgroud)
Please refer to documentation for more details.
如果您直接引用 User(例如,通过在外键中引用它),您的代码将无法在 AUTH_USER_MODEL 设置已更改为不同用户模型的项目中工作。
get_user_model()[来源]
您应该使用 django.contrib.auth.get_user_model() 来引用用户模型,而不是直接引用 User。此方法将返回当前活动的用户模型 - 如果指定了自定义用户模型,否则为 User。
当您为用户模型定义外键或多对多关系时,您应该使用 AUTH_USER_MODEL 设置指定自定义模型。例如