在Django(postgress)中删除模型时删除了什么?

2024-09-26 22:07:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一本模型书:

class Books(models.Model):
    name = models.Charfield()
    author = models.Charfield()

后来我建立了另一个叫做BookReviews的模型,它链接到书籍:

class BookReviews(models.Model):
    book = models.ForeignKey(Books)
    content = models.TextField()

但我搞砸了,我想完全删除书评范本。当我跑的时候

python manage.py migrate

我收到一条警告信息:

Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types?

这是否意味着,即使那些条目在书评之前就已经存在,任何链接到书中的条目也会被删除?你知道吗


Tags: to模型youmodel链接models条目content
1条回答
网友
1楼 · 发布于 2024-09-26 22:07:16

我想你想知道on_delete中的ForeignKey选项

When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

删除Books对象时,会删除所有外部BookReviews对象,因为on_delete=models.CASCADE是默认值。您的型号如下

    class Books(models.Model):
            name = models.Charfield()
            author = models.Charfield()

    class BookReviews(models.Model):
            book = models.ForeignKey(
                    Books,
                    on_delete=models.CASCADE,
            )
            content = models.TextField()

如果不想自动删除BookReviews,可以使用其他on_delete选项,如下所示

    class BookReviews(models.Model):
            book = models.ForeignKey(
                    Books,
                    on_delete=models.SET_NULL,
                    blank=True,
                    null=True,
            )

django文档中有许多有用的示例,因此请查看here以获取更多信息。你知道吗

P.S. after django 2.0 version, you should write on_delete option when writing FroeignKey field.

相关问题 更多 >

    热门问题