在创建包含标题、内容和作者的帖子模型时,我author = models.ForeignKey(User, on_delete=models.CASCADE)
为作者写作,因为一个作者可以拥有多个帖子。我的问题是为什么传递给on_delete
参数的函数没有执行。换句话说,为什么on_delete=models.CASCADE()
不是(注意括号)?
因为那样的话,你会立即在翻译时看到评价功能models.CASCADE
。
这个想法是我们将一个函数传递给on_delete
参数,而不是调用该函数的结果,这样以后,当User
被删除时,Django 框架将调用该函数来收集引用该用户的对象,并将这些对象删除为好。
因此,这意味着我们不会在您运行服务器时调用该函数,或者我们可以多次调用它。此外,触发器函数需要参数:
def CASCADE(collector, field, sub_objs, using): collector.collect(sub_objs, source=field.remote_field.model, source_attr=field.name, nullable=field.null) if field.null and not connections[using].features.can_defer_constraint_checks: collector.add_field_update(field, None, sub_objs)
在collector
这里收集应删除(并递归一直这样做)额外的对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句