Search code examples
pythondjangodjango-modelsforeign-keysmodels

How can I set user full name in foreignkey field with User Model using on_delete attribute?


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.


Solution

  • user field in News Model maps to a User 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 the News model and populate it when creating the News instance.

    class News(models.Mode):
        user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL)
        name = models.CharField()
    
        def save(self, *args, **kwargs):
            if not self.id:
                self.name = self.user.first_name + self.user.last_name
            super(News, self).save(*args, **kwargs)
    

    Now when User is deleted, user field is set to NULL and name field contains the required name information.