简体   繁体   中英

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?

And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is "on_delete=models.CASCADE" do and mean?

And is this code ( from django.contrib.auth.models ) a database for users?

models.DateTimeField(default=timezone.now) do, what does "default" mean here?

You can pass a callable to the default=… parameter. 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 .

And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is on_delete=models.CASCADE do and mean?

A ForeignKey refers to an object. 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. CASCADE means that it will remove the Post (s) from a User , if that User is removed itself.

And is this code ( from django.contrib.auth.models ) a database for users?

These are models defined in the auth app. Django has such app to make it easy to start with a simple user model, but you can decide to impelement your own. 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. For more information you can see the referencing the User model section of the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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