25đź‘Ť
that’s the default behaviour, yes. you can change this behaviour with on_delete
to get an illustration of this, try deleting a userprofile in the admin. it first shows a warning page, listing all related objects that will also get deleted
202đź‘Ť
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 theUserProfile
, all relatedPhoto
s 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 aUserProfile
with relatedPhoto
s, raising adjango.db.models.ProtectedError
if you try. The idea would be that the user would need to disassociate or delete allPhoto
s before they could delete their profile. -
SET_NULL
: when you delete theUserProfile
, all associatedPhoto
s will still exist but will no longer be associated with anyUserProfile
. This would requirenull=True
in theForeignKey
definition. -
SET_DEFAULT
: when you delete theUserProfile
, all associatedPhoto
s will be changed to point to their defaultUserProfile
as specified by thedefault
attribute in theForeignKey
definition (you could use this to pass “orphaned” photos off to a certain user – but this isn’t going to be common,SET_NULL
orSET()
will be much more common) -
SET()
: when you delete theUserProfile
, the target of thePhoto
s’ForeignKey
will be set to the value passed in to theSET
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 theUserProfile
, all relatedPhoto
s 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.)
- [Django]-Difference between different ways to create celery task
- [Django]-How to set current user to user field in Django Rest Framework?
- [Django]-Django 'Sites' Model – what is and why is 'SITE_ID = 1'?