django.db.models.ForeignKey.on_delete

I’ll go through the values for on_delete as they apply to this case. As it notes in the docs, these are all in that models module, so you’d use it as models.ForeignKey(UserProfile, on_delete=models.CASCADE), etc.

These rules apply however you delete an object, whether you do it in the admin panel or working directly with the Model instance. (But it won’t take effect if you work directly with the underlying database in SQL.)

CASCADE: when you delete the UserProfile, all related Photos will be deleted too. This is the default. (So in answer to that aspect of your question, yes, if you delete your user account the photos will be deleted automatically.)

PROTECT: this will stop you from deleting a UserProfile with related Photos, raising a django.db.models.ProtectedError if you try. The idea would be that the user would need to disassociate or delete all Photos before they could delete their profile.

SET_NULL: when you delete the UserProfile, all associated Photos will still exist but will no longer be associated with any UserProfile. This would require null=True in the ForeignKey definition.

SET_DEFAULT: when you delete the UserProfile, all associated Photos will be changed to point to their default UserProfile as specified by the default attribute in the ForeignKey definition (you could use this to pass “orphaned” photos off to a certain user - but this isn’t going to be common, SET_NULL or SET() will be much more common)

SET(): when you delete the UserProfile, the target of the Photos’ ForeignKey will be set to the value passed in to the SET function, or what it returns if it is a callable. (Sorry, I haven’t explained that well, but the docs have an example which explains better.)

DO_NOTHING: when you delete the UserProfile, all related Photos will remain unaltered, thus having a broken reference, unless you have used some other SQL to take care of it.

(Also, on_delete isn’t a method. It’s an attribute of the ForeignKey field.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值