python - Django 中的 "auth.User"是做什么的?

标签 python django authentication

我正在尝试学习 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 .

通常,字符串模型名称用于以下情况:

  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

关于python - Django 中的 "auth.User"是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715518/

相关文章:

python - 通过 matplotlib 线图绘制一组多项式趋势线

python - 使用非整数变量创建 Django URL 模式

authentication - 在默认 Laravel 5.0 AuthController 中允许用户名而不是电子邮件

authentication - 如何告诉具有多个证书的 LDAP SSL 服务器返回我需要的证书?

ruby-on-rails - 是否可以将登录用户存储在 Ruby on Rails 的 session 中?

Python:对休眠线程的惩罚

python - 安装后 cx_freeze 无法获取 zip 导入器

python - 从 PySpark 数组列中删除重复项

python - 如何使用 Sudo 在生产服务器上配置 Django 电子邮件

django "duplicate key value violates unique constraint"主键