I have a model in django that have foreignkey with User model.
class News(models.Model):
user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET(???))
message - models.TextField()
So When any user account delete from database then in News table entries also deleted according to user. So I want that When any user account deleted then I need to set his/her full name in user field using 'on_delete=models.SET(???)'
Example:
If I have user that first_name = 'Neeraj' and last_name='Kumar' When I want to delete that user account then in News table I want to save his name.
As in the previous answer, you cannot assign string value into ForeignKey field. With this on_delete approach, you can assign a special user something like deleted in this case. Furthermore, if you really want to assign user's name into another field, you can do it with Django signal. There is nothing can do about with on_delete.
user
field inNews
Model maps to aUser
Model instance.You cannot assign a string to this field. You can only assign either null a
User
model instance.You will have to provide a substitute user to put in place of the deleted user. So either reserve a user for substitution or create one at the time of deletion. It is explained very clearly in the docs.
One thing you can do is to add a new
name
field to theNews
model and populate it when creating theNews
instance.Now when
User
is deleted,user
field is set to NULL andname
field contains the required name information.