我正在尝试学习 Django,我在书中发现了以下代码。
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
尽管我理解了其中的大部分内容,但我并不真正理解 "auth.User"
在代码中的作用。此外,我尝试在文档中搜索它,但没有成功(我觉得很奇怪)。
预先非常感谢您的帮助。
最佳答案
'auth.user' 是 Django 应用程序的模型 https://docs.djangoproject.com/en/2.1/ref/contrib/auth/ 。在您的代码中,您使用了字符串“auth.User”作为外键。我对代码进行了一些修改,以从 auth 应用程序显式导入用户模型。
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 接受带有模型类名或模型类本身的字符串。 https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.ForeignKey .
通常,字符串模型名称用于以下情况:
-
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
关于python - Django 中的 "auth.User"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715518/