[英]What gets deleted when I delete a model in django (postgress)?
Lets say I have a model Books: 可以说我有一个样板书:
class Books(models.Model):
name = models.Charfield()
author = models.Charfield()
and later I set up another model called BookReviews which links to Books: 然后我建立了另一个名为BookReviews的模型,该模型链接到Books:
class BookReviews(models.Model):
book = models.ForeignKey(Books)
content = models.TextField()
But I messed up and I want to delete model BookReviews completely. 但是我搞砸了,我想完全删除模型BookReviews。 When I run
当我跑步
python manage.py migrate
python manage.py迁移
I get a warning message: 我收到警告消息:
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?
您确定要删除这些内容类型吗?
Does that mean any entries linked to in Books will also be deleted even if those entries existed before BookReviews? 这是否意味着即使在BookReviews之前就存在与Book中链接的所有条目,这些条目也会被删除?
I think you wonder about on_delete
option in ForeignKey
我认为您想知道
ForeignKey
on_delete
选项
When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument.
删除由ForeignKey引用的对象时,Django将模拟on_delete参数指定的SQL约束的行为。 For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:
例如,如果您有一个可为空的ForeignKey,并且希望在删除引用的对象时将其设置为null:
When deleting your Books
object, all foreign BookReviews
objects deleted because on_delete=models.CASCADE
is default. 删除
Books
对象时,所有外部BookReviews
对象都被删除,因为默认为on_delete=models.CASCADE
。 your model is same as below 您的型号与以下相同
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()
If you don't want automatically delete BookReviews
, you can use other on_delete
options, like this 如果您不想自动删除
BookReviews
,可以使用其他on_delete
选项,例如
class BookReviews(models.Model):
book = models.ForeignKey(
Books,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
There's many useful example in django documentation, so check here for more information. django文档中有许多有用的示例,因此请在此处查看更多信息。
PS after django 2.0 version, you should write
on_delete
option when writing FroeignKey field.django 2.0版本之后的PS,在编写FroeignKey字段时应编写
on_delete
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.