Difference between User models

Viewed 47

I'm learning django now, watch tutorials. The questions is: What is the difference between using:

from django.contrib.auth import get_user_model User = get_user_model()

User = get_user_model()

and
from django.contrib.auth.models import User

I've seen both of them and both of them used in model with ForeignKey, but I don't know the difference between these two model, for example:

    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts'
    )
    title = models.CharField(max_length=100)
    text = models.TextField()```
1 Answers

The get_user_model() function [Django-doc] will return a reference to the class that you set in the AUTH_USER_MODEL setting [Django-doc]. By default this is 'auth.User', so the model of the django.contrib.auth.models module, but you can specify a different user model.

It is however better to make use of the settings.AUTH_USER_MODEL to refer to the user model, than to use User or get_user_model(), as is specified in the referencing the User model section of the documentation, you thus work with:

from django.conf import settings

class Post(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='posts'
    )
    # …
Related