Reputation: 4783
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.
Upvotes: 2
Views: 4009
Reputation: 1434
'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:
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
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
To refer to models defined in another application, you can explicitly specify a model with the full application label
Upvotes: 4
Reputation: 12581
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.
Upvotes: 2