简体   繁体   中英

What does “auth.User” in Django do?

I'm trying to learn Django and I came across the following code in the books.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=􏰃􏰂􏰂) 
    author = models.ForeignKey(
        'auth.User',
        on_delete=models.CASCADE,
      )

    body = models.TextField() 

    def __str__(self):
         return self.title

Even though I understand the most part of it I don't really understand what does "auth.User" do in the code. Furthermore, I tried searching for it in the documentation without any success (Which I found quite strange).

Thank you very much in advance for your help.

The 'auth.User' specifier indicates what model the ForeignKey maps to. So, with the given model, each Post record will have a column named author_id (the _id suffix is automatically added by Django under the covers), and will point to an entry in the User table in the auth application (which is a built-in application).

See the documentation on ForeignKey for more.

'auth.user' is the model of the auth application which is part of Django https://docs.djangoproject.com/en/2.1/ref/contrib/auth/ . In your code, you used the string 'auth.User' for ForeignKey. I modified the code a bit to explicitly import the User model from the auth application.

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=􏰃􏰂􏰂) 
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
    )

    body = models.TextField() 

    def __str__(self):
        return self.title

ForeignKey accepts string with class name of the model or model class itself. https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.ForeignKey .

Typically, string model names are used in the following cases:

  1. If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself

  2. Relationships defined this way on abstract models are resolved when the model is subclassed as a concrete model and are not relative to the abstract model's app_label

  3. To refer to models defined in another application, you can explicitly specify a model with the full application label

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM