models.ForeignKey() 在 Django 中
models.ForeignKey() in django
这是我的代码
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
所以我对 models.DateTimeField(default=timezone.now)
的作用有点困惑,这里的“默认”是什么意思?
而且我也很困惑 models.ForeignKey(User, on_delete=models.CASCADE)
是做什么的,“on_delete=models.CASCADE”是什么意思?
这段代码(from django.contrib.auth.models
)是用户的数据库吗?
models.DateTimeField(default=timezone.now)
do, what does "default" mean here?
您可以将可调用对象传递给 default=…
参数。当创建模型对象时,date_posted
没有值,它将调用 timezone.now
函数并将结果用作 date_posted
.
的值
And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE)
do, what is on_delete=models.CASCADE
do and mean?
一个ForeignKey
引用了一个对象。问题是如果它所指的对象被删除了怎么办。使用 on_delete=…
[Django-doc] 您可以指定一个策略。 CASCADE
表示它将从 User
中删除 Post
(s),如果 User
本身被删除。
And is this code ( from django.contrib.auth.models ) a database for users?
这些是 auth
应用程序中定义的模型。 Django 有这样的应用程序,可以很容易地从一个简单的用户模型开始,但是你可以决定实现你自己的。通常最好使用 settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use the User
model [Django-doc] directly. For more information you can see the referencing the User
model section of the documentation.
这是我的代码
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
所以我对 models.DateTimeField(default=timezone.now)
的作用有点困惑,这里的“默认”是什么意思?
而且我也很困惑 models.ForeignKey(User, on_delete=models.CASCADE)
是做什么的,“on_delete=models.CASCADE”是什么意思?
这段代码(from django.contrib.auth.models
)是用户的数据库吗?
models.DateTimeField(default=timezone.now)
do, what does "default" mean here?
您可以将可调用对象传递给 default=…
参数。当创建模型对象时,date_posted
没有值,它将调用 timezone.now
函数并将结果用作 date_posted
.
And I'm also confused what
models.ForeignKey(User, on_delete=models.CASCADE)
do, what ison_delete=models.CASCADE
do and mean?
一个ForeignKey
引用了一个对象。问题是如果它所指的对象被删除了怎么办。使用 on_delete=…
[Django-doc] 您可以指定一个策略。 CASCADE
表示它将从 User
中删除 Post
(s),如果 User
本身被删除。
And is this code ( from django.contrib.auth.models ) a database for users?
这些是 auth
应用程序中定义的模型。 Django 有这样的应用程序,可以很容易地从一个简单的用户模型开始,但是你可以决定实现你自己的。通常最好使用 settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use the User
model [Django-doc] directly. For more information you can see the referencing the User
model section of the documentation.