简体   繁体   English

django 中的models.ForeignKey()

[英]models.ForeignKey() in django

Here is my code这是我的代码

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)

So I'm kinda confused with what models.DateTimeField(default=timezone.now) do, what does "default" mean here?所以我有点困惑models.DateTimeField(default=timezone.now)做什么,“默认”在这里是什么意思?

And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is "on_delete=models.CASCADE" do and mean?而且我也很困惑models.ForeignKey(User, on_delete=models.CASCADE)做什么,“on_delete=models.CASCADE”是什么意思?

And is this code ( from django.contrib.auth.models ) a database for users?这段代码( from django.contrib.auth.models )是用户数据库吗?

models.DateTimeField(default=timezone.now) do, what does "default" mean here? models.DateTimeField(default=timezone.now)做,这里的“默认”是什么意思?

You can pass a callable to the default=… parameter.您可以将可调用对象传递给default=…参数。 When the model object is the created, and there is no value for date_posted , it will call the timezone.now function and use the result as value for the date_posted .当模型对象被创建,并且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?而且我也很困惑models.ForeignKey(User, on_delete=models.CASCADE)做什么, on_delete=models.CASCADE做什么和意味着什么?

A ForeignKey refers to an object. ForeignKey是指一个对象。 The question is what to do if the object it is referring to is removed.问题是如果它所指的对象被删除了该怎么办。 With on_delete=… [Django-doc] you can specify a strategy.使用on_delete=… [Django-doc]你可以指定一个策略。 CASCADE means that it will remove the Post (s) from a User , if that User is removed itself. CASCADE意味着它将从User删除Post (s),如果该User本身被删除。

And is this code ( from django.contrib.auth.models ) a database for users?这段代码(来自 django.contrib.auth.models )是用户数据库吗?

These are models defined in the auth app.这些是在auth应用程序中定义的模型。 Django has such app to make it easy to start with a simple user model, but you can decide to impelement your own. Django 有这样的应用程序,可以很容易地从一个简单的用户模型开始,但你可以决定实现你自己的。 It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly.通常最好使用settings.AUTH_USER_MODEL [Django-doc]来引用用户模型,而不是直接使用User模型 [Django-doc] For more information you can see the referencing the User model section of the documentation .有关更多信息,您可以查看文档引用User模型部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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