I have a question while creating a long-range model.

Asked 2 years ago, Updated 2 years ago, 45 views

By importing user models

(1)

from django.conf import settings

uesr = settings.AUTH_USER_MODEL

(2)

from django.contirb.auth import get_user_model

user = get_user_model()

What's the difference between (1) and (2)?

python django

2022-09-20 11:14

1 Answers

1) For the first time, the corresponding settings.The string value of the user model specified in AUTH_USER_MODEL is retrieved.

2) In the case of the number of times, the user object applied with the user model itself is imported.

Therefore, you can write number 1 when you import only the path to the app, and number 2 when you need the object itself. For example, when you need ForeignKey, you can use it because you need a model path (?) rather than an entire object in the field below, and you can use it like the bottom if you need a specific field in user.

Example 1

model_exam = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Custom", on_delete=models.CASCADE)

Example #2

user = get_user_model()
print(user.username)


2022-09-20 11:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.