据我所知,当我们在Django中定义外键时,我们可以设置为like on_delete=models.CASCADE
。
最近我看过类似的代码content_type = models.ForeignKey(ContentType,models.CASCADE)
。
我的问题是django是否允许在不使用on_delete的情况下定义model.CASCADE?或者,如果我们像上面那样定义,它的工作方式是否有所不同?
content_type = models.ForeignKey(
ContentType,
models.CASCADE,
verbose_name=_('content type'),
)
是的,我们可以做到。
为了清楚地理解它,请尝试理解以下代码:
def fn(x, y, z=0):
print('x =', x, 'y =', y, 'z =', z)
fn(1, 2) # Prints: x = 1 y = 2 z = 0
fn(1, 2, 3) # Prints: x = 1 y = 2 z = 3
fn(1, y=2) # Prints: x = 1 y = 2 z = 0
fn(1, y=2, z=3) # Prints: x = 1 y = 2 z = 3
fn(x=1, y=2) # Prints: x = 1 y = 2 z = 0
fn(x=1, y=2, z=3) # Prints: x = 1 y = 2 z = 3
fn(y=2, z=3, x=1) # Prints: x = 1 y = 2 z = 3
现在,看看ForeignKey的源代码。看起来像这样:
class ForeignKey(ForeignObject):
...
def __init__(
self, to, on_delete,
related_name=None, related_query_name=None,
limit_choices_to=None, parent_link=False,
to_field=None, db_constraint=True, **kwargs,
):
...
所以,当我们写:
content_type = models.ForeignKey(
ContentType,
models.CASCADE,
verbose_name=_('content type'),
)
参数to
为ContentType
,参数on_delete
为models.CASCADE
。
这与写作完全相同:
content_type = models.ForeignKey(
on=ContentType,
on_delete=models.CASCADE,
verbose_name=_('content type'),
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句